我有一个在域 A 上运行的 Express JS 服务器。它托管静态文件,包括一些图像和 JavaScript 模块。我在服务器上安装了 CORS 中间件,以确保仅允许来自已批准的域的请求。 CORS 选项会根据允许的域列表检查请求的来源。当这些允许的域之一上的页面使用 img 标记并将其 src 设置为 Express 服务器上图像的路径时,Express 服务器将返回 500 错误。这似乎是因为浏览器没有为请求设置原始标头,而只是设置引用。
服务器文件结构:
root
- images
- modules
app.js
package.json
package-lock.json
Express 服务器代码:
const express = require('express');
const cors = require('cors');
const app = express();
const allowedOrigins = [/\.domainb\.com$/, /\.domainc\.com$/];
const testOrigin = function (origin) {
let allowed = false;
for (var i = 0; i < allowedOrigins.length; i++) {
if (allowedOrigins[i].test(origin)) {
allowed = true;
}
}
return allowed;
};
const corsOptions = {
credentials: true,
origin: function (origin, callback) {
if (testOrigin(origin)) {
console.log('corsOptions has true test result');
callback(null, true);
} else {
callback(new Error(origin + ' is not on list of allowed origins'));
}
},
};
// cors pre-flights
app.options('*', cors());
app.use(cors(corsOptions));
app.use(express.static('modules'));
app.use(express.static('images'));
module.exports = app;
app.listen(8000, () => {
console.log(`Express server listening on port 8000`);
});
不确定此处的选项是否是尝试测试 CORS 选项中的引用标头、绕过静态图像或其他内容的 CORS。
一种可能的解决方案是将 crossorigin 属性添加到 HTML 文件中的
img
标记(假设可以),浏览器将在请求中包含 Origin
标头并检查 CORS 权限。
一旦执行此操作,任何没有 Origin 标头的请求都可以被安全地拒绝,因为它不是来自您的客户端页面。
<img crossorigin="anonymous | use-credentials" src="http..." />