节点js POST不使用React获取数据

我正在提交一个表单,下面被称为…

handleLogin(){ fetch('http://localhost:8080', { method: 'post', body: JSON.stringify({ username: this.state.username, password: this.state.password }) }); } 

它向我的restAPI发出POST请求。 请求的作品,但数据不传递…

 app.post('/', function(req, res, next) { console.log(req.body.username); .... 

这将打印出未定义的,这意味着密码和用户名不会通过调用。 我究竟做错了什么?

快速默认不分析请求的主体。 为了启用parsing,您将需要使用一个中间件,如body-parser 。 您可以在快速文档中find一些信息。

此外,客户端需要指出它正在发送json数据。 这可以通过Content-Type头来实现。 这里有一个很好的关于fetch()教程。 您可以直接跳转到与您的问题相关的Request Headers部分。

  var express = require("express"); var app = express(); var bodyParser = require('body-parser'); const PORT = process.env.PORT || 7070; const BASEURL = process.env.BASEURL || 'http://localhost/7070'; app.use(bodyParser.urlencoded({extended:true})); app.listen(PORT, function() { console.log('Server running on'+BASEURL); });