突然之间,我所有的项目都出现了这种情况。

每当我在nodejs中使用express和body-parser req发布帖子时。Body是一个空对象。

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

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded())

// parse application/json
app.use(bodyParser.json())

app.listen(2000);

app.post("/", function (req, res) {
  console.log(req.body) // populated!
  res.send(200, req.body);
});

通过ajax和邮递员,它总是空的。

但是通过curl

$ curl -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:2000/

它按预期工作。

我尝试在前者中手动设置Content-type: application/json,但我总是得到400个坏请求

这快把我逼疯了。

我以为是身体解析器更新了一些东西,但我降级了,它没有帮助。

感谢任何帮助,谢谢。


当前回答

我只是解决了为app.use()删除任何.json()或.urlencode()的问题,因为它们给了我一些问题。我用这个简单的解决方案编写了我的代码来重新创建流

app.post('/mypath',function(req,res){
   data=""
   // we can access HTTP headers
   req.on('data', chunk => {
      data+=chunk
   })
   req.on('end', () => {
      console.log(data)
      // here do what you want with data
      // Eg: js=JSON.parse(data)
   })
}

其他回答

谢谢大家的精彩回答! 花了相当多的时间寻找解决方案,在我这边,我犯了一个基本的错误:我从函数内部调用bodyParser.json():

app.use([' /密码'],异步(点播,res,下一个)= > { bodyParser.json () /…… next () })

我只需要做app.use(['/password'], bodyParser.json()),它工作…

我发现,它的工作时,发送内容类型

“应用程序/ json”

与服务器端结合 app.use (express.json ()) (正如@marcelocra指出的那样,2022年的版本将使用)

(旧版本供参考) app.use (bodyParser.json ());

现在我可以通过发送

var data = {name:"John"}
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", theUrl, false); // false for synchronous request
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(data);

结果在服务器上的request.body.name中可用。

我使用的是restify而不是express,遇到了同样的问题。解决办法是:

server.use(restify.bodyParser());

当表单不包含任何文件上传输入时,请确保您已经删除了表单标记处的enctype属性

enctype='multipart/form-data

表达4.17.1

这样的服务器中间件示例没有bodyParser;

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

如果你是GET请求头应该是这样的;

{'Content-Type': 'application/json'}

如果你是POST请求头应该像这样;

{'Content-Type': 'application/x-www-form-urlencoded'}

我在客户端使用这样的简单函数;

async function _GET(api) {
    return await (await fetch(api, {
        method: 'GET',
        mode: 'no-cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Connection': 'keep-alive',
            'Accept': '*',
        },
    })).json();
};

async function _POST (api, payload) {
    return await (await fetch(api, {
        method: 'POST',
        mode: 'no-cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Connection': 'keep-alive',
            'Accept': '*/*',
        },
        body: new URLSearchParams(payload),
    })).json();
};