更新#2:这个问题已经解决了,请参阅我自己的答案(我还不能接受)。
我正在 Heroku 上通过 Express 使用 Node.js 后端运行 React 应用程序。在前端,我想发送一个包含 JSON 负载的 POST 请求,发送方式如下:
fetch('/api/shows', {
method: 'POST',
accept: 'application/json',
headers: new Headers({
'Content-Type': 'application/json',
}),
// mode: 'cors', // tried this, but no effect
// cache: 'default', // tried this, but no effect
body: JSON.stringify({ "foo": "bar" }),
}).then(response => {
return response.json();
}).then(response => {
// … handling the response …
}).catch(err => {
// … handling errors …
});
后端设置如下:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('port', (process.env.PORT || 3001));
if (process.env.NODE_ENV === 'production') {
app.use(express.static('frontend/build'));
}
app.post('/api/shows', bodyParser.json(), (req, res) => {
const data = req.body;
console.log(data); // shows {}
});
在本地,这一切都工作正常,但部署在 Heroku 上,请求的内容类型为 application/x-www-form-urlencoded
而不是 application/json
,这就是 body-parser 中间件不解析 JSON 的原因。
奇怪的是,几天前,当我尝试过一次时,这个确实起作用了,但我不知道在此期间我在这方面做了任何更改。
尽管为请求显式设置了 header ,但是什么导致 header 错误?我可以配置中间件来读取它,但这似乎是一个解决方法。我想了解问题的实际根本原因。
更新#1
我认为这可能与 URL 设置有关。使用来自命令行的curl请求来服务后端,使用http://my-app.herokuapp.com/api/shows时接收到数据,但使用 http://myurl.info/api/shows 时则不然.
最佳答案
就像经常发生的情况一样,在发布后不久我就弄清楚了。该问题实际上与应用程序无关。
我通过提供商使用自己的 URL,并设置了指向 myapp.herokuapp.com 的重定向,结果证明这是问题所在。 Heroku explains in detail如何为 Heroku 应用程序配置域,并按照该过程使用 CNAME 条目后,一切正常。
关于javascript - fetch() header 显示为 application/x-www-form-urlencoded 而不是 application/json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44429838/