简体   繁体   中英

post data in node.js

I have a HTML file that includes:

<form method="post" action="localhost:3000/post">
   <input name="user[name]" type="text"/>
   <button type="submit">sub</button>
</form>

And in my node app.js file I write this lines for posting:

app.post("/post" ,function(req ,res ){
   console.log(req.body.user.name);
   res.send(req.body.user.name);
});

But I can't post that data.

After searching I found that I have to add this lines to node files:

var bodyParser = require('body-parser');
app.use(express.bodyParser());

I install it with "npm install body-parser".But an error occurs.

How can I fix this?

If you're using express 4, bodyParser is no longer bundled with it. So you have to change this line :

app.use(express.bodyParser());

With this one:

app.use(bodyParser());

You can find more informations and exemples here :

https://github.com/expressjs/body-parser

FOR SERVER PART

If you've installed body-parser through npm-install successfully.

Adding these lines in you app.js should work

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());

If gives warning like

body-parser deprecated urlencoded: explicitly specify "extended: true" for extended parsing

use following

app.use(bodyParser.urlencoded({
   extended: true
}));

In Your Client

In Your HTML you are saying that action="localhost:3000/post" . I think this changed to

/post if you have to make request on same server

OR

action="http://localhost:3000/post If you are making request to some other server.

Try something liek this

To install try with sudo as I have found issues installing things without such at times:

sudo npm install body-parser

Then in your code if the above hasn't failed, something lie this:

var app = express().use(require('body-parser')());
app.post("/post" ,function(req ,res ){
   console.log(req.body.user.name);
   res.send(req.body.user.name);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM