I have a simple HTML file like this :
<form method="post" action="http://localhost:3000/post">
<input name="name" type="text"/><br />
<input name="last_name" type="text"/><br />
<button id="submit" type="submit">Submit</button>
</form>
I receive post data with this node (express) code :
app.route('/post')
.post(function(req, res, next) {
res.send(req.body.name);
});
for example for this input :
Richard Stallman
I receive something like this :
["Richard","Stallman"]
But I need them like this :
{ name : "Richard" ,last_name : "Stallman" }
Or something like this.
How can I fix it?
I have to use req.body instead of req.body.name, and it will give me each index and its value.Like a json file.
The right way to approach getting posted data in Express is to use express body parser.
This will give you an object with the keys matching your named form fields (as you appear to desire).
You'll probably want the application/x-www-form-urlencoded parser.
app.use(bodyParser.urlencoded({ extended: false }))
If you're using GET as the method on the form, you can pull the object straight out of express using req.query without any extra middleware.
So if the form sends the following request:
www.mysite.com/input?name=richard&last_name=stallman
Your req.query will be {name: 'richard', last_name: 'stallman'}