node.js - 通过获取请求访问服务器时,express JS cors 中间件不起作用
问题描述
服务器位于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 标头设置成功。
我在互联网上搜索了很多解决方案,似乎没有任何效果。我错过了什么吗?
谢谢你的帮助。
解决方案
如果您有一个代理集,请确保它被设置为http://localhost:3001
. 之后调整你fetch
只使用部分网址,如下所示:
fetch("/user", {
method: "GET",
headers: {
"Content-Type": "application/json"
}
}).then(response => {
console.log(response);
});
删除它也应该是安全的:
const cors = require("cors");
var corsOptions = {
origin: "http://localhost:3000",
optionsSuccessStatus: 200
};
推荐阅读
- html - 如何在多个 html 页面(或使用记事本++)中找到所有这种 UNICODE �?
- javascript - 来自 event.preventDefault() 和 event.stopPropagation() 的 Firebase 身份验证网络错误?
- doctrine - 如何构建动态学说查询?
- kotlin - mockK 不能区分每个语句中的类型
- mongodb - 如何根据mongodb聚合中数组内的另一个字段有条件地将值设置为父字段?
- java - MacOs Catalina 10.15.5 崩溃并且报告没有给出任何线索
- swift - 带有 SwiftUI 的 tvOS 上的 NavigationLink 按钮不起作用
- autodesk-forge - 如何从 Autodesk Forge Viewer 打开 PDF 的缓冲区数据
- multithreading - 哪些用例适合 Kotlin 中的 Dispatchers.Default?
- sql - 连接多个小表时,如何提高 Snowflake 中 SQL 查询的性能?