资源上没有'Access"/>
即使在设置后仍然出现“请求的资源上没有'Access
我正在尝试在我的 nodejs 服务器中设置一些逻辑来捕获端点,并从服务器中与端点匹配的目录中返回静态文件。 IE。如果有人点击
/styles/style.json
,返回在/styles/style.json
找到的文件,或者从端点/styles/image.png
返回/styles/image.png
,从/styles/<some_file>
端点返回/styles/<some_file>
。我没有使用 express,我正在按照 Node.js 快速文件服务器(HTTP 上的静态文件) 找到的建议来执行此操作。
我从 FE 收到 CORS 错误:
从来源“”获取“http://localhost:5000/styles/styles.json”的访问已被 CORS 策略阻止:无“Access-Control-Allow-Origin”标头存在于请求的资源上。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
但是我确实在我的服务器端代码中设置了这个标头:
const http = require("http");
const path = require("path");
const fs = require("fs");
const stylejson = require("./styles/style-local.json");
const requestListener = function (req, res) {
const headers = {
"Access-Control-Allow-Origin": "*", // <----- set it right here!
"Access-Control-Allow-Methods": "OPTIONS, POST, GET",
"Access-Control-Max-Age": 2592000,
"Content-Type": "application/json",
};
// This tactic works with no CORS errors, does not allow for dynamic endpoints
if (req.url == "/styles/styles.json") {
res.writeHead(200, headers);
res.end(JSON.stringify(stylejson));
return;
}
// Allows for dynamic endpoints, but gives CORS errors:
if (req.url.startsWith("/styles/")) {
const filePath = "." + req.url;
const ext = path.extname(req.url);
if (ext === "png") {
headers["Content-Type"] = "image/png";
}
fs.readFile(filePath, function (error, content) {
if (error) {
if (error.code == "ENOENT") {
res.writeHead(404, headers);
res.end();
return;
} else {
res.writeHead(500, headers);
res.end("Sorry, check server for error: " + error.code + " ..\n");
return;
}
} else {
console.log(headers); // <---- this logs and clearly shows the header is set!
res.writeHead(200, headers);
res.end(content);
return;
}
});
}
}
const server = http.createServer(requestListener);
server.listen(port);
当我明确检查 url 并通过
res.end(JSON.stringify())
发送 JSON 时它有效,但当我尝试使用 fs.readFile
时不起作用。
我在这里错过了什么?好像我正在设置它应该设置它。
编辑
添加图像以显示在浏览器中发生此错误的请求:
回答如下:看起来问题与提供非 JSON 文件时的内容类型标头有关。默认情况下,您将标头设置为“application/json”,但是在提供 PNG 文件时,您没有正确更新内容类型。
Node 文档 说:
方法返回路径的扩展,从最后一次出现的 . (句点)字符到路径最后部分中字符串的结尾。如果没有。在路径的最后一部分,或者如果没有 .路径的基本名称的第一个字符以外的字符(见path.extname()
),返回一个空字符串。path.basename()
在这段代码片段中,您还可以看到
path.extname()
返回带有句点的扩展名。
所以,而不是这一行:
if (ext === "png") {
headers["Content-Type"] = "image/png";
}
你应该使用:
if (ext === ".png") {
headers["Content-Type"] = "image/png";
}
此外,对于其他文件类型,您应该正确设置
Content-Type
。这是一个更完整的例子:
const getContentType = (ext) => {
switch (ext) {
case ".json":
return "application/json";
case ".png":
return "image/png";
// Add more cases for other file types if needed
default:
return "application/octet-stream";
}
};
// ...
if (req.url.startsWith("/styles/")) {
const filePath = "." + req.url;
const ext = path.extname(req.url);
headers["Content-Type"] = getContentType(ext);
// ...
}
这样,您就可以根据文件扩展名正确设置
Content-Type
标头,它应该可以解决您遇到的 CORS 错误。
更多推荐
即使在设置后仍然出现“请求的资源上没有'Access
发布评论