Cant enable CORS on the server side NodeJS

坚强是说给别人听的谎言 提交于 2020-08-10 18:52:29

问题


I can't enable CORS on the server-side. My frontend and backend servers have different ports. Here is how server-side is implemented:

http
  .createServer(function (req, res) {
    // .. Here you can create your data response in a JSON format
    // const { headers, method, url } = req;
    // let body = [];
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Request-Method', '*');
    res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
    res.setHeader('Access-Control-Allow-Headers', '*');
    if (req.method === 'OPTIONS') {
      res.writeHead(200);
      res.end();
      return;
    }

    // const responseBody = { headers, method, url, body: JSON.stringify(data) };

    response.write('{asd: 123}'); // Write out the default response
    res.end(); //end the response
  })
  .listen(port);

And I call the fetch function from the frontend-side like this one:

fetch('http://localhost:3035', {
      method: 'POST',
      mode: 'same-origin', // no-cors, *cors, same-origin
      cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
      credentials: 'include', // include, *same-origin, omit
      headers: {
        'Content-Type': 'application/json',
        // 'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: JSON.stringify(line), // body data type must match "Content-Type" header
    })
      .then((response) => response.json())
      .then((data) => console.log(data))
      .catch((error) => console.log(error));

But still getting errors:

Security Error: Content at http://localhost:3030/ may not load data from http://localhost:3035/.

TypeError: "NetworkError when attempting to fetch resource."


回答1:


You explicitly disallowed CORS on the client side by setting mode: 'same-origin' instead of the default mode: 'cors'.

To quote the docs:

same-origin — If a request is made to another origin with this mode set, the result is simply an error. You could use this to ensure that a request is always being made to your origin.

Since http://localhost:3035/ is another origin than http://localhost:3030/, the result is, exactly as designed, "simply an error".

Set it to mode: 'cors' or remove mode entirely since cors is the default anyway.


On a side note, Access-Control-Request-Method is a request header in the preflight request, not a response header. You should remove it.


As mentioned in the comments: For a credentialed request to work, you cannot use an allowed origin of *. If you don't want to hardcode the expected origin at this point though, you can avoid this problem by always returning the origin that the current request comes from, using res.setHeader('Access-Control-Allow-Origin', req.headers.origin).



来源:https://stackoverflow.com/questions/63088444/cant-enable-cors-on-the-server-side-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!