Express.js req.body undefined

前端 未结 30 2497
半阙折子戏
半阙折子戏 2020-11-22 12:02

I have this as configuration of my Express server

app.use(app.router); 
app.use(express.cookieParser());
app.use(express.session({ secret: \"keyboard cat\" }         


        
相关标签:
30条回答
  • 2020-11-22 12:36

    Credit to @spikeyang for the great answer (provided below). After reading the suggested article attached to the post, I decided to share my solution.

    When to use?

    The solution required you to use the express router in order to enjoy it.. so: If you have you tried to use the accepted answer with no luck, just use copy-and-paste this function:

    function bodyParse(req, ready, fail) 
    {
        var length = req.header('Content-Length');
    
        if (!req.readable) return fail('failed to read request');
    
        if (!length) return fail('request must include a valid `Content-Length` header');
    
        if (length > 1000) return fail('this request is too big'); // you can replace 1000 with any other value as desired
    
        var body = ''; // for large payloads - please use an array buffer (see note below)
    
        req.on('data', function (data) 
        {
            body += data; 
        });
    
        req.on('end', function () 
        {
            ready(body);
        });
    }
    

    and call it like:

    bodyParse(req, function success(body)
    {
    
    }, function error(message)
    {
    
    });
    

    NOTE: For large payloads - please use an array buffer (more @ MDN)

    0 讨论(0)
  • 2020-11-22 12:38

    The Content-Type in request header is really important, especially when you post the data from curl or any other tools.

    Make sure you're using some thing like application/x-www-form-urlencoded, application/json or others, it depends on your post data. Leave this field empty will confuse Express.

    0 讨论(0)
  • 2020-11-22 12:38

    Most of the time req.body is undefined due to missing JSON parser

    const express = require('express');
    app.use(express.json());
    

    could be missing for the body-parser

    const bodyParser  = require('body-parser');
    app.use(bodyParser.urlencoded({extended: true}));
    

    and sometimes it's undefined due to cros origin so add them

    const cors = require('cors');
    app.use(cors())
    
    0 讨论(0)
  • 2020-11-22 12:39
    var bodyParser = require('body-parser');
    app.use(bodyParser.json());
    

    This saved my day.

    0 讨论(0)
  • 2020-11-22 12:41

    As already posted under one comment, I solved it using

    app.use(require('connect').bodyParser());
    

    instead of

    app.use(express.bodyParser());
    

    I still don't know why the simple express.bodyParser() is not working...

    0 讨论(0)
  • 2020-11-22 12:42

    in Express 4, it's really simple

    const app = express()
    const p = process.env.PORT || 8082
    
    app.use(express.json()) 
    
    0 讨论(0)
提交回复
热议问题