【发布时间】:2017-02-20 18:43:33
【问题描述】:
我正在使用 react 将数据发送到我的 API。我发出的每个 POST 请求都会给我一个 OPTIONS 请求,我需要解决这个问题。我想我可能需要做一些预检结构,但在阅读后我仍然不知道如何实现它。
目前我正在连接到我的 API...
fetch('http://localhost:8080/login', {
method: 'POST',
mode:'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password
})
});
这称为onSubmit。我正在向我的 POST 请求发送一些数据,所以我假设我需要这些标头。
现在在我的节点 js 服务器 API 中,我有以下处理程序...
var responseHeaders = {
"access-control-allow-origin": "*",
"access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
"access-control-allow-headers": "content-type, accept",
"access-control-max-age": 10,
"Content-Type": "application/json"
};
app.post('/login', function(req, res, next) {
if (req.method == "OPTIONS") {
res.writeHead(statusCode, responseHeaders);
res.end();
}
console.log("hello");
...
但是,这不起作用,当我提出请求时,我得到...
OPTIONS /login 200 8.570 ms - 4
如果我删除了 POST 的标题,但数据(用户名、密码)没有通过。
如何绕过这个 OPTIONS 问题?
【问题讨论】: