【发布时间】:2021-11-02 22:10:22
【问题描述】:
我收到错误 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at 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 npm 包:npmjs.com/package/cors
-
OP 正在使用
corsnpm 包。配置和支持 CORS 不是问题;是 Web 浏览器的安全模型不允许对 localhost 资源的 CORS 请求。
标签: javascript express cors