how to send back a post to a generated site - javascript

I'm trying to generate a page with the post connected to an id, I've got the id in to the node function witch I can see in the console but i don't know how i can render a new view with this posts content?
thankful for all ideas!
i think something is wrong with the search do to the fact that I don't get the item value in the console
in my node js file
router.param('id', function(req,res, next, id){
console.log(req.params.id)
db.collection('insights').find({_id:req.params.id}).toArray(function (err, items) {
res.json(items);
console.log(items)
});
res.send(items);
});
router.get('/share/:id', function(req, res) {
res.render('contact');
});

The param() callback is generally not for directly responding to requests (although maybe in case of error). It's to be used for loading data from databases, etc.
Here's what you might do:
router.param('id', function(req, res, next, id) {
db.collection('insights')
.find({_id: id})
.toArray(function(err, items) {
if (err) {
console.error(err);
return res.send(404);
}
req._items = items;
next();
});
});
router.get('/share/:id', function(req, res) {
res.render('contact', { items: req._items });
});

Related

I am creating a full stack tinder clone, I can't read and write data inn the database

i am sending both get and post request none of them are being executing
here is the snippet
app.get('/', (req,res)=> res.status(200).send('hello'));
app.post('/tinder/cards', (req, res)=>{
const dbCard = req.body;
Cards.create(dbCard, (err, data)=>{
if(err){
res.status(500).send(err)
}else{
res.status(201).send(data)
}
})
});
app.get('/tinder/cards', (req, res)=>{
Cards.find((err, data)=>{
if(err){
res.status(500).send(err)
}else{
res.status(200).send(data)
}
})
})
the first get request is being executing properly and sending response but the rest two aren't working
I dont know what to do, I should get an empty array when i hit a get request

Node.js Express execute inside app.post()

I have a problem right now that I can't solve by myself. I assume you know more here. I'm just getting started.
By using the following code I'm getting a list of customers:
app.get("/customers", customers.findAll);
I wanted to add authentication. But now I don't know how to execute "customers.findAll" and get the value as JSON.
app.get("/customers", verifyToken, (req, res) => {
jwt.verify(req.token, 'justAtest, (err, authData) => {
if (err) {
res.sendStatus(403);
} else {
// execute customers.findAll
}
});
});
Customers is integrated via a requirement
const customers = require("../controllers/customer.controller.js");
The contents are as follows:
exports.findAll = (req, res) => {
Customer.getAll((err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while retrieving customers."
});
else res.send(data);
});
};
Do you have any ideas?
Thank you in advance.
Grettings
Rok
You achieve that using something called "middleware". Explore it since it is very important.
Basically :
app.get("/customers", verifyToken,customers.findAll);
Wherre verify token is a funtion that has 3 parameters: req, res and 3rd one called "next".
So your verify token function would look something like:
(req, res,next) => {
jwt.verify(req.token, 'justAtest, (err, authData) => {
if (err) {
res.sendStatus(403);
} else {
next();
}
});
}
I took it from your snippet. Basically if you want to jump to customeeers.finalAll, just call "next" and it jumps to next function :D.

Node.js send JSON to client

I am new to Node.js and javascript. I have a problem which I can't solve. I have a Node application, also I am using Express.
My problem: I have a script that sends a JSON to my server. This data is then stored in my MongoDB. What i want to do now is display that data on another page. This is what i have:
router.post('/', function(req, res, next) {
MongoClient.connect(url, function(err, db) {
var dbase = db.db("db");
dbase.collection('db').insertOne(req.body, function (err, result) {
if (err)
console.log('error');
else
console.log('success');
res.render('result');
});
});
});
What would be the best way to display the data stored in req.body? And could I send it to 'result'? Or should I display the data within the InsertOne-Function?
Please read the express documentation for all the details.
The JSON response can be sent using res.json() method.
Your code will look like this -
router.post('/', function(req, res, next) {
MongoClient.connect(url, function(err, db) {
var dbase = db.db("db");
dbase.collection('db').insertOne(req.body, function (err, result) {
if (err)
console.log('error');
else
res.json(result);
});
});
});

How to redirect to view page using mongoDB and node.js

I am new with node.js, mongoDB and jade.
To redirect to userlist page I have following route in /routes/index.js
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
This route redirects me to userlist page. There I display a list of all users. Here I have a link on each record to view details:
following is my userlist.jade
extends layout
block content
h1.
User List
ul
each user, i in userlist
li
a(href="/viewuser/id/#{user._id}")=user.username
This:
a(href="/viewuser/id/#{user._id}")=user.username
Gives me:
Dhara
Now I don't know what route should be there for view details on click of the link and how to get selected record data for view screen.
I use a clear and distributed stack MEAN.js, with a yeoman constructor that will help you to build secure and good-practice programming applications.
This is the way I get a concrete user data. It´s a little more spread than your code but it´s clear.
Hope it helps!
routes.js
app.use('/api/users', require('./api/user'));
api/user/index.js
var controller = require('./user.controller');
router.get('users/:id', controller.show);
user.controller.js:
// Get a single user
exports.show = function(req, res) {
User.findById(req.params.id, function (err, user) {
if(err) { return handleError(res, err); }
if(!user) { return res.send(404); }
return res.json(user);
});
};
then I´ll call for a user with an url like users/xxxxxx where xxxx is the user id. Then if you want to do it like /viewuser/id/xxxxxx you will need to change the route like this:
api/user/index.js
var controller = require('./user.controller');
router.get('viewuser/id/:id', controller.show);
user.controller.js:
// Get a single user
exports.show = function(req, res) {
User.findById(req.params.id, function (err, user) {
if(err) { return handleError(res, err); }
if(!user) { return res.send(404); }
return res.json(user);
});
};
maybe you need to specify the view in your app server file
app.get('/userlist', function(req, res){
res.render('userlist', {
title: 'Your_Title'
});
});
I hope to be helpful!

Node.js - "TypeError - res.setHeader is not a function"

I'm trying to load JSON from a URL to a variable and send it back to the client's javascript
var getJSON =require('get-json');
app.post('/json', function(req, res) {
getJSON(url, function(err, res){
if(err)
{
console.log(err);
}
else
{
res.setHeader('content-type', 'application/json');
res.send(JSON.stringify({json: res.result}));
}
});
});
Every time I run the code the server says that res.setHeader isn't a function and the rest breaks.
Both post and getJSON callbacks have same res variable name.
Try this:
var getJSON =require('get-json');
app.post('/json', function(req, res) {
getJSON(url, function(err, response){
if(err)
{
console.log(err);
}
else
{
res.setHeader('content-type', 'application/json');
res.send(JSON.stringify({json: response.result}));
}
});
});
for me this was happening when fetching data in a forum i built. i found the fix to this in this blogpost:
https://dev.to/shailesh6363/facing-error-res-setheader-not-a-function-2oc9
i added code according to atul singh in the comments.
changes in app.js
app.use((res, next) => {
....
});
to
app.use((req, res, next) => {
....
});
now the app doesnt crash and it sucessfully fetches and displays the data

Categories