[英]node js POST not getting data using React
I am submitting a form and the following gets called...我正在提交一个表格,以下内容被调用...
handleLogin(){
fetch('http://localhost:8080', {
method: 'post',
body: JSON.stringify({
username: this.state.username,
password: this.state.password
})
});
}
It makes a POST request to my restAPI.它向我的 restAPI 发出 POST 请求。 The request works, but the data is not passed...
请求有效,但数据未通过...
app.post('/', function(req, res, next) {
console.log(req.body.username);
....
This prints out undefined, meaning password and username are not passed through the call.这会打印出 undefined,这意味着不会通过调用传递密码和用户名。 What am I doing wrong?
我究竟做错了什么?
Express by default doesn't parse the body of the request. Express 默认不解析请求的正文。 In order to enable parsing, you will need to use a middleware such as body-parser .
为了启用解析,您需要使用诸如body-parser 之类的中间件。 You can find some information in the express docs .
您可以在express 文档中找到一些信息。
Also, the client side needs to indicate that it's sending json
data.此外,客户端需要表明它正在发送
json
数据。 That can be achieved with the Content-Type
header.这可以通过
Content-Type
标头来实现。 There is a pretty good tutorial about fetch()
here .有一个关于一个很好的教程
fetch()
在这里。 You can jump directly to the Request Headers
section which is relevant for your question.您可以直接跳转到与您的问题相关的
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.