我只需要创建一个Node服务器来接收POST请求。 有了请求正文中的信息,我需要创建一个系统调用。 我该怎么办? 到目前为止,我只有:
var express = require('express'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser); app.post('/', function(req, res){ console.log('POST /'); console.dir(req.body); }); port = 3000; app.listen(port); console.log('Listening at http://localhost:' + port)但是,当我向127.0.0.1:3000发出POST请求时,正文是未定义的。
var request = require('request');
request.post( '127.0.0.1:3000', { form: { "user": "asdf" } }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) } } );I need to create a Node server only for receiving POST requests. With the information in the body of the request, I need to create a system call. How do I do so? So far, I only have:
var express = require('express'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser); app.post('/', function(req, res){ console.log('POST /'); console.dir(req.body); }); port = 3000; app.listen(port); console.log('Listening at http://localhost:' + port)However, when I make a POST request to 127.0.0.1:3000, the body is undefined.
var request = require('request');
request.post( '127.0.0.1:3000', { form: { "user": "asdf" } }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) } } );最满意答案
你在这里遇到了中间件问题。 express.bodyparser()中间件在Express 4.x中已弃用。 这意味着您应该使用独立的bodyparser中间件。
奇怪的是,您通过执行以下操作导入正确的中间件:
var bodyParser = require('body-parser');
但是,您应该以不同的方式使用它。 看一下文档和给出的例子:
var app = require('express')(); var bodyParser = require('body-parser'); var multer = require('multer'); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.use(multer()); // for parsing multipart/form-data app.post('/', function (req, res) { console.log(req.body); res.json(req.body); })You've got a middleware problem here. The express.bodyparser() middleware is deprecated in Express 4.x. This means you should be using the standalone bodyparser middleware.
Oddly enough, you're importing the correct middleware by doing:
var bodyParser = require('body-parser');
However, you should be using it differently. Take a look at the docs and the example given:
var app = require('express')(); var bodyParser = require('body-parser'); var multer = require('multer'); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.use(multer()); // for parsing multipart/form-data app.post('/', function (req, res) { console.log(req.body); res.json(req.body); })更多推荐
发布评论