I have this POST route:
router.post("/form", (req, res) => {
const data = req.body;
});
I need to be able to pass the data coming from a form submitting to the POST route to the GET route:
router.get("/form", (req, res) => {
// How can I use 'data' here?
console.log(data);
});
How possibly could this be achieved?
Related
I want to send data from my config.js file to every single render. Is there a way to do this with a few lines of code instead of having to manually push the data with every single render function?
Here's what I mean
const data = require("config.js").coolData;
app.get("/", (req, res) => {
res.render("index", {data});
});
app.get("/request2", (req, res) => {
res.render("index", {data);
});
app.get("/request3", (req, res) => {
res.render("index", {foo, data);
});
Is there a way to easily send data to all three?
If you are using express, you can do it with res.locals; in a middleware For example:
const data = require("config.js").coolData;
app.use((req, res, next) => {
res.locals.data = data;
next();
});
...
Just be sure to place the middleware above before any other route
I am able to have both /apply and /register going to the same action using (note it's a regex and not a string):
app.get(/apply|register/, (req, res) => {
// ...
res.send("OK");
});
How do I write the route to make both "/apply/:id" and "/register/:id" go to the same action?
Use an array.
app.get(['/apply/:id', '/register/:id'], (req, res) => {
// ...
res.send("OK");
});
My function in the controller:
getWeather: (req, res) => {
const userId = req.params.userId;
weather.save().then(() => {
console.log('weather saved')
}).catch(error => { return res.status(500).json({ error }) })
}
The middleware in the model, here I want to get the userId as a param
weatherSchema.pre('save', function (req, res, next) {
console.log( req + ' pre!! '); //req
next();
})
I don't succeed, I tried to look for similar questions but their answers did not help me. What can I try next?
I guess you're confused between express middleware and mongoose middleware. The save mongoose middleware that you are using is a document middleware and it only gets a single parameter i.e. next and it is triggered before .save().
I guess an express middleware would solve your problem.
app.get("/someroute", (req, res, next) => {
// Here you have access to req.params.userId
next();
}, (req, res) => {
// Here you can save it to the db
})
When I hit the signup route "req.body" doesn't pick any up any of the POST values, however whenever the same code is tested on Postman - with body raw method - the values display.
const router = require('express').Router();
const bodyParser = require('body-parser');
const Promise = require('bluebird');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({
extended: true
}));
const registration = require('./services/registration');
router.get('/', (req, res, next) => {
res.send('Admin Welcome');
});
router.get('/signup', (req, res, next) => {
res.render('user/signup');
});
router.post('/signup', (req, res, next) => {
res.send(req.body);
registration.registration(req.body);
.then(ok=>{
res.redirect('signin')
})
.catch(err => {
res.render('error', {message: err})
})
})
router.get('/signin', (req, res, next) => {
res.render('user/signin');
});
original code
router.post("/signup", (req, res, next) => {
res.send(req.body);
registration
.registration(req.body)
.then(ok => {
res.redirect("signin");
})
.catch(err => {
res.render("error", { message: err });
});
});
The res object represents the HTTP response that an Express app sends when it gets an HTTP request. In the following link you can see all the methods that are exposed for res object:
https://expressjs.com/en/api.html#res
Method that you are using at the beginning of you route handler is:
res.send([body])
And as it can be read from the documentation it sends the HTTP response. Now you can send that response only once, otherwise you will get an error:
Error : Cannot set headers after they are sent to the client
And what you are trying to do in the handler is to redirect result to "signin" page afterwards already sending the response with res.send(req.body).
Take this fake route for an example:
router.post("/example", (req, res, next) => {
res.send('1');
res.send('2');
res.send('3');
});
Contrary to what you might believe, it wont return values (1,2,3), but actually return value 1 and raise and error that was previously described.
Finally to solve your issue you need to remove line containing res.send(req.body) and double check if registration.registration service is correctly handling provided data, in this case req.body.
I am executing the following code in node.js. The code runs fine, but the tutorial tells us that :
Now go back and add the Content-Type header with a value of application/json and run the request again. You will get the “You sent
JSON” message back from the server.
1) I am not able to understand how can I set headers for this program!
2) Also If I am running the program without setting headers, then the message 'Server requires application/json' should be displayed. I am not seeing it being displayed anywhere. Where should it be displayed?
const express = require('express');
const app = express();
const requireJsonContent = () => {
return (req, res, next) => {
if (req.headers['content-type'] !== 'application/json') {
res.status(400).send('Server requires application/json')
} else {
next()
}
}
}
app.get('/', (req, res, next) => {
res.send('Welcome Home');
});
app.post('/', requireJsonContent(), (req, res, next) => {
res.send('You sent JSON');
})
app.listen(3000);
What I see In Your code is that, the function requireJsonContent that you defined Does not have parameters. So, you should add (req, res, next) as params to your function. Besides, inside it, you return a function without execution. However, I think You don't need that function, and your code should be like this:
app.post('/', (req, res) => {
if (req.headers['content-type'] !== 'application/json') {
res.status(400).send('Server requires application/json')
} else {
res.send('You sent JSON');
}
})
With express 4.x, you can either use res.set() or res.append(). Read differences between both methods here.