【发布时间】:2021-02-22 23:46:35
【问题描述】:
我正在使用 fetch web API 从 reactJS 发送一个 post 方法请求,以在具有不同端口的本地主机上表达 NodeJS 服务器。
客户端获取 API
fetch("http://localhost:8081/test",
{
method: "post",
mode:"no-cors",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username : "John Doe",
password : "It's a secret"
})
}).then(function(response)
{
if(response.ok)
{
return response.json();
}else
{
console.log(response)
}
}).then(function(body) { console.log(body); }).catch((error) => { console.log(error) });
服务器 - Express NodeJS
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors())
app.post('/test', function (req, res)
{
return res.send({ message: 'Any response' });
})
我从客户端收到我的 POST 数据没有问题,但我没有收到服务器的响应。几乎尝试了所有方法,但我在响应时收到此错误
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
任何帮助表示赞赏。
【问题讨论】:
-
我敢肯定,如果您查看您的 chrome 开发工具,您会收到 CORS 政策错误,您可以检查一下吗?
-
你试过删除
mode:"no-cors",吗?您可以在这里阅读更多信息:stackoverflow.com/questions/43262121/… -
该死,@mehowthe,我很感激你,没想到这个。你拯救了我的一天!
标签: javascript node.js reactjs express fetch