[英]Unable to fetch data with fetch() from React Client to Nodejs Server
所以这是我的客户:
handleSubmit(event) { event.preventDefault(); alert(`starting to stream ${this.state.value} at ${this.state.volume}`) fetch('/emitter', {
method: 'post',
body: JSON.stringify({
value: this.state.value,
volume: this.state.volume
}),
headers: {"Content-Type": "application/json"}
});
alert(`${this.state.value} and ${this.state.volume} sent to server`) };
这是我的服务器:
app.use(express.static(__dirname + '/build'));
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/emitter', function (req, res) {
console.log(req.body)
});
我只是想将数据从输入表单发送到服务器。 当我在服务器中收到req.body
时,为什么我得到一个空的{}
?
编辑:
作为参考,这是答案: https : //github.com/github/fetch/issues/323#issuecomment-277510957
app.use(bodyParser.json());
需要在之后或之前添加:
app.use(bodyParser.urlencoded({
extended: true
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.