【发布时间】:2020-05-31 21:49:06
【问题描述】:
所以我遇到了这个奇怪的问题。我有一个托管在服务器上的 Node/Angular 应用程序,在同一个端口上工作。但仅在一个页面上,存在 CORS 错误。
到目前为止,我已经在 app.js 中的 routes 之前添加了允许的 CORS。
代码:
const apiRoutes = require("./routes/api");
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Content-Type, Authorization, Content-Length, X-Requested-With, cache-control"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET,POST,PATCH,DELETE,OPTIONS,PUT"
);
next();
})
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/uploads', express.static(path.join(__dirname, './uploads')));
app.use('/api', apiRoutes);
我也使用了 cors npm 包并允许它使用它,但仍然没有运气。
附上同目录获取同一张图片的请求参数。
Response param when the image is accessed on page 1
Response param when the same image is blocked CORS
编辑:
const cors = require('cors');
app.use(cors());
app.options('*', cors());
这个我也用过,但是也没用。
来自同一来源的请求被阻止,
Access to image at 'https://www.pay2mate.com/uploads/1579836295281-Affinity_Logo.png' from origin 'https://pay2mate.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
【问题讨论】:
-
www.pay2mate.com和pay2mate.com实际上是同一台服务器吗?如果是这样,您为什么不直接从www.pay2mate.com而不是pay2mate.com运行您的前端应用程序?如果您这样做,它们将是同源的,并且您不需要启用 CORS 的服务器。 -
@sideshowbarker 非常感谢。我已经被困在这里 2 天了。
标签: node.js angular image cors