代码之家  ›  专栏  ›  技术社区  ›  Seth Lutske

即使设置了“请求的资源上不存在”Access Control Allow Origin“标头”,仍会出现错误

  •  0
  • Seth Lutske  · 技术社区  · 3 年前

    我试图在nodejs服务器中设置一些逻辑来捕获端点,并从服务器中与端点匹配的目录中返回静态文件。也就是说,如果有人打 /styles/style.json ,返回在中找到的文件 /styles/style.json ,或返回 /styles/image.png 从端点 /样式/image.png 回来 /styles/<some_file> 来自 /样式/<some_file> 端点。我没有使用快递,我遵循的建议在 Node.js quick file server (static files over HTTP) 这样做。

    我收到FE的CORS错误:

    访问“”获取http://localhost:5000/styles/styles.json'来自原点'https://somesandbox.csb.app'已被CORS策略阻止:请求的资源上不存在“Access Control Allow Origin”标头。如果不透明响应满足您的需求,请将请求的模式设置为“无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()) ,但当我尝试使用时不起作用 fs.readFile

    我在这里错过了什么?似乎我正在按应该设置的方式设置它。

    编辑

    添加图像以在浏览器中显示发生此错误的请求: enter image description here

    0 回复  |  直到 3 年前