Node.js(带有 express 和 bodyParser):无法从 post 请求中获取表单数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26347394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:00:05  来源:igfitidea点击:

Node.js (with express & bodyParser): unable to obtain form-data from post request

node.jsexpresspostmultipartform-databody-parser

提问by Jem

I can't seem to recover the form-data of a post request sent to my Node.js server. I've put below the server code and the post request (sent using postman in chrome):

我似乎无法恢复发送到我的 Node.js 服务器的 post 请求的表单数据。我已经把服务器代码和发布请求(在 chrome 中使用邮递员发送)放在下面:

Post request

发布请求

POST /api/login HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="userName"

jem
----WebKitFormBoundaryE19zNvXGzXaLvS5C

NodeJS server code

NodeJS服务器代码

var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

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

app.all('/*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type,accept,access_token,X-Requested-With');
    next();
});

var port = process.env.PORT || 8080;        // set our port

var router = express.Router();              // get an instance of the express Router

router.get('/', function(req, res) {

    res.json({ message: 'I am groot!' });   
});

// Login
router.route('/login')

    .post(function(req, res){

        console.log('Auth request recieved');

        // Get the user name
        var user = req.body.userName;

        var aToken = getToken(user);

        res.json({

            'token':'a_token'
        });
    });

app.use('/api', router);

app.listen(port);

The login method tries to obtain the req.body.userName, however, req.bodyis always empty. I've seen other cases on SO describing such behavior but none of the related answers did apply here.

login 方法尝试获取req.body.userName,但是,req.body始终为空。我在 SO 上看到其他案例描述了这种行为,但没有一个相关的答案在这里适用。

Thanks for helping out.

感谢您的帮助。

采纳答案by cybersam

In general, an express app needs to specify the appropriate body-parser middlewarein order for req.bodyto contain the body.

一般来说,1个Express应用程序需要指定适当的身体解析器的中间件,以便req.body遏制身体。

[EDITED]

[编辑]

  1. If you required parsing of url-encoded (non-multipart) form data, as well as JSON, try adding:

    // Put this statement near the top of your module
    var bodyParser = require('body-parser');
    
    
    // Put these statements before you define any routes.
    app.use(bodyParser.urlencoded());
    app.use(bodyParser.json());
    

    First, you'll need to add body-parserto the dependenciesproperty of your package.json, and then perform a npm update.

  2. To handle multi-part form data, the bodyParser.urlencoded()body parser will not work. See the suggested modules herefor parsing multipart bodies.

  1. 如果您需要解析 url 编码(非多部分)表单数据以及 JSON,请尝试添加:

    // Put this statement near the top of your module
    var bodyParser = require('body-parser');
    
    
    // Put these statements before you define any routes.
    app.use(bodyParser.urlencoded());
    app.use(bodyParser.json());
    

    首先,您需要将body-parser添加到 的dependencies属性中package.json,然后执行npm update.

  2. 要处理多部分表单数据,bodyParser.urlencoded()正文解析器将不起作用。请参阅此处建议模块以解析多部分主体。

回答by Sanjeev Kumar

To handle multipart/form-data request that support file upload, you need to use multer module. npm link for multer middleware

要处理支持文件上传的 multipart/form-data 请求,您需要使用 multer 模块。multer 中间件的 npm 链接

回答by Aecio Levy

Make sure to put in this order: bodyParser.json() first. app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));

确保按以下顺序排列: bodyParser.json() 首先。 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));

回答by user3444748

I followed this https://www.tutorialspoint.com/expressjs/expressjs_form_data.htm

我跟着这个 https://www.tutorialspoint.com/expressjs/expressjs_form_data.htm

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

// apply them

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

// how to use

router.post('/', function(req, res) {
    console.log(req.body);
    console.log('received the widget request');
});

回答by Saifio

Make sure you are not sing enctype as multipart/form-data, body parser does not support it. use below line before you define any route.

确保您没有将 enctype 唱为 multipart/form-data,正文解析器不支持它。在定义任何路线之前使用下面的行。

app.use(bodyParser.urlencoded()); app.use(bodyParser.json());

app.use(bodyParser.urlencoded()); app.use(bodyParser.json());