I've a form with express.js:
app.get("/", function (req, res) {
if (req.body.something) {
// Do something
}
res.send(myform);
});
app.post("/", function (req, res) {
if (req.body.foobar == false) {
// I need to set req.body.something and make it visible to "get"
}}
});
My form:
<form method="post" action="/">
<input type="checkbox" name="foobar">
<input type="submit" value="submit">
</form>
I need a way to send data with "post" method and make it visible by the "get" method. How can I do?
There are probably a number of ways to do this. One option is to store the POST values in a session.
app.post("/", function (req, res) {
if (req.body.foobar == false) {
//Store foobar from body of POST into the session
req.session.foobar = req.body.foobar;
// Other stuff...
}}
});
app.get("/", function (req, res) {
if (req.body.something) {
// Do something
doStuff(req.session.foobar) // Here we use the foobar set in POST
//DO MORE STUFF
}
res.send(myform);
});
To use this before add something similar to below enable sessions.
app.use(session({secret: 'fabecefd-387c-4dc9-a525-25d1fab00330'}));
More Documentation on https://github.com/expressjs/session
Additional note: Please validate your input, handle error conditions, and structure your code your own way. The above was a very basic example on how to use sessions.
You can send data with the GET method using jQuery :
$.ajax({
type: 'GET',
data: 'Your body content here'
});
Or using curl from a terminal :
curl -XGET -d "Your body content" http://localhost:3000/
app.get("/", function (req, res) {
if (req.body.something) {
app.get('setKey');
}
res.json(req.body);
});
app.post("/", function (req, res) {
if (req.body.foobar == false) {
app.set('setKey','setValue');
}}
});