Cant get request payload in express js node

后端 未结 5 910
终归单人心
终归单人心 2021-01-17 23:06

This is my Node Express Code,

(function () {
    \'use strict\';
    var fs = require(\'fs\');
    var cors = require(\'cors\');
    var bodyParser = requir         


        
5条回答
  •  礼貌的吻别
    2021-01-17 23:36

    You need to send: Content-Type: application/json for bodyParser.json() to work, without it, your JSON payload won't be parsed, that's why you get: {}

    From the docs:

    The bodyParser object exposes various factories to create middlewares. All middlewares will populate the req.body property with the parsed body when the Content-Type request header matches the type option, or an empty object ({}) if there was no body to parse, the Content-Type was not matched, or an error occurred.

    Example using .fetch:

    fetch('http://localhost:4200/dashboard', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({dd: 'dd'})
    });
    

提交回复
热议问题