为什么 CORS 在简单的 Express 应用程序中不起作用
Why doesn't CORS work in a simple Express app
我无法在示例 React/Express 应用程序中消除此浏览器错误:
Access to fetch at 'http://localhost:9000/getFiles' from origin 'http://localhost:3000' has been blocked by CORS policy: 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.
其中 /getFiles 从 React 调用 API 到 Express。
我进行了大量谷歌搜索,我认为我已经正确编码了所有内容。
App.js:
import express from 'express';
import routes from './routes/index.js'
import cors from "cors";
const app = express();
app.use(cors());
app.use("/", routes);
const PORT = 9000;
app.listen(PORT,() => {
console.log(`Running on PORT ${PORT}`);
})
我怀疑它与 ES6 格式有关,但我看到其他代码示例完全按原样使用该导入语句。
我明白了。问题是因为我在设置路由后错误地添加了 cors() 引用。颠倒顺序并重新启动我的应用程序后,它开始工作了。
正确顺序:
...
app.use("/", routes);
app.use(cors());
...
this 文章的支持,让我走上了正确的轨道。
我无法在示例 React/Express 应用程序中消除此浏览器错误:
Access to fetch at 'http://localhost:9000/getFiles' from origin 'http://localhost:3000' has been blocked by CORS policy: 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.
其中 /getFiles 从 React 调用 API 到 Express。
我进行了大量谷歌搜索,我认为我已经正确编码了所有内容。
App.js:
import express from 'express';
import routes from './routes/index.js'
import cors from "cors";
const app = express();
app.use(cors());
app.use("/", routes);
const PORT = 9000;
app.listen(PORT,() => {
console.log(`Running on PORT ${PORT}`);
})
我怀疑它与 ES6 格式有关,但我看到其他代码示例完全按原样使用该导入语句。
我明白了。问题是因为我在设置路由后错误地添加了 cors() 引用。颠倒顺序并重新启动我的应用程序后,它开始工作了。
正确顺序:
...
app.use("/", routes);
app.use(cors());
...
this 文章的支持,让我走上了正确的轨道。