【发布时间】:2019-07-23 01:44:10
【问题描述】:
服务器在http://localhost:3001,客户端相同,但端口为3000。
在客户端我运行简单的获取,我需要从服务器获取登录的用户数据,目前我只是使用 GET 方法(GET,POST,没有工作)这样做(我还必须包括 cookie) :
fetch("http://localhost:3001/user", {
method: "GET",
credentials: "include",
headers: {
"Content-Type": "application/json"
}
}).then(response => {
console.log(response);
});
还有服务器:
const cors = require("cors");
var corsOptions = {
origin: "http://localhost:3000",
optionsSuccessStatus: 200
};
app.get("/user", cors(corsOptions), function(req, res, next) {
u_session = req.session;
const db_result = db
.collection("users")
.findOne({ email: u_session.email }, function(err, result) {
if (err) throw err;
res.json({ email: result.email, type: result.type });
});
});
我得到的是 cors 错误:
Access to fetch at 'http://localhost:3001/user' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
另外,如果我通过浏览器访问服务器 URL,我可以看到 access-allow-control-allow-origin 标头设置成功。
我在互联网上搜索了很多解决方案,但似乎没有任何效果。我错过了什么吗?
感谢您的帮助。
【问题讨论】:
-
我之前在使用 Create react app 和 fetch 时遇到了这个错误(可能不是同一个问题,但可能是一个有用的类比)。解决方案是将代理设置为后端服务器 url,并从获取请求中删除 localhost:<port>。我不必以这种方式处理任何 CORS 选项。
-
@MattPengelly 哦,天哪,我在这上面浪费了多少时间,忘记了在客户端的 packaje.json 中设置了代理。非常感谢!