跨域请求阻塞:同源策略不允许读取远程资源' localhost:..- ExpressJS和npm Cors



我得到了错误跨域请求阻塞:同源策略不允许在localhost:...读取远程资源使用下面的示例代码,我如何修复它?,我只是遵循文档和stackoverflow的任何指南,但没有人工作。

我使用npm中的cors模块。

// Init express application
const app = express();
// Setup cors for cross domain requests
const whitelist = [
"http://localhost:3002/", // frontend curr localhost port
"http://localhost:5500/", // live server url
];
// eslint-disable-next-line
const corsOptions = {
origin: function (origin, callback) {
// allow if the origin is undefined,
// means has the same origin, the result
// is undefined because the request
// is coming from the same origin.
if (!origin) return callback(null, true);
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error("CORS not allowed"));
}
},
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
methods: ["GET", "PUT", "POST", "DELETE", "OPTIONS"],
credentials: true, //Credentials are cookies, authorization headers or TLS client certificates.
allowedHeaders: [
"Content-Type",
"Authorization",
"X-Requested-With",
"device-remember-token",
"Access-Control-Allow-Origin",
"Origin",
"Accept",
],
};
app.options("*", cors(corsOptions));
app.use(cors(corsOptions));
// END SECURITY CONFIG
// Route for monolithic app
const web = require("./routes/web");
// Route for microservices app
const api = require("./routes/api");
// Route for unit testing
const test = require("./routes/test");

您无法在代码中修复此问题。这是你的网络架构的配置问题,你的浏览器正在执行适当的安全性。

很长一段时间以来,浏览器默认不允许本地主机的CORS。

不正确的解决方法是在浏览器中禁用CORS检查。对于Chrome,它是将--disable-web-security添加到程序可执行文件中,即创建一个Chrome快捷方式(Windows)到"C:Program Files (x86)GoogleChromeApplicationchrome.exe" --disable-web-security

解决这个问题的正确方法是不要让在浏览器上运行的客户端代码使用localhost连接到api服务器,而是正确配置环境以通过主机名公开服务器。

有无数的方法可以做到这一点,这取决于您如何运行您的服务器和客户端,但如果您只是在同一台机器上运行您的客户端和服务器进行开发和调试,您应该只需要在您的hosts文件中添加一个条目,该条目将主机名解析为127.0.0.1。

然后更新代码将test.mydomain.com列入白名单

127.0.0.1 localhost
127.0.0.1 test.mydomain.com

相关内容

最新更新