2

I am trying to set up some logic in my nodejs server to catch an endpoint, and return static files from within a directory in the server that match the endpoint. I.e. if someone hits /styles/style.json, return the file found at /styles/style.json, or return /styles/image.png from the endpoint /styles/image.png, return /styles/<some_file> from the /styles/<some_file> endpoint. I am not using express, and I am following advice found at Node.js quick file server (static files over HTTP) to do this.

I am getting CORS errors from the FE:

Access to fetch at 'http://localhost:5000/styles/styles.json' from origin 'https://somesandbox.csb.app' 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.

But I did set this header in my server-side code:

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);

It works when I explicitly check the url and send JSON through res.end(JSON.stringify()), but does not work when I try to use fs.readFile.

What am I missing here? Seems like I am setting it as it should be set.

Edit

Adding image to show which request this error is happening on in the browser: enter image description here

Seth Lutske
  • 9,154
  • 5
  • 29
  • 78
  • `const ext = path.extname(req.url);` — what's `path` here? – Pointy Apr 28 '23 at 23:19
  • @Pointy Sorry, I edited the question to include the imports, its the nodejs `path` module – Seth Lutske Apr 28 '23 at 23:22
  • 1
    Are you sure you're responding to the preflight `OPTIONS` request? Check the browser's Network tab to see what's happening. – Barmar Apr 28 '23 at 23:24
  • @Barmar I did a double check and it doesn't look like it, but maybe I'm not 100% understanding what you mean. Added a snap of the network requests to the question, doesn't look like its on the preflight? – Seth Lutske Apr 28 '23 at 23:30

0 Answers0