【问题标题】:How to create Node server only for POST requests如何仅为 POST 请求创建节点服务器
【发布时间】:2015-07-16 16:44:01
【问题描述】:

我只需要创建一个节点服务器来接收 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)
        }
    }
);

【问题讨论】:

  • 你实际的 POST 请求是什么样的?
  • 您使用的是哪个版本的节点?
  • @Tholle - 我使用 Post 请求(在 Node 中)编辑了问题正文。
  • 使用 bodyParser 作为中间件,如下所示,如果您仍然面临问题,请务必告知。

标签: javascript node.js express


【解决方案1】:

这里有一个中间件问题。 express.bodyparser() 中间件在 Express 4.x 中已弃用。这意味着您应该使用独立的 bodyparser 中间件。

奇怪的是,您正在通过以下方式导入正确的中间件:

var bodyParser = require('body-parser');

但是,您应该以不同的方式使用它。看看the docs 和给出的例子:

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);
})

【讨论】:

    【解决方案2】:
    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);
    })
    

    在最新版本的 express 中,没有使用 express.bodyParser。见reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 2021-10-18
      • 1970-01-01
      • 2014-05-18
      • 2019-01-08
      相关资源
      最近更新 更多