无法在服务器端NodeJS上启用CORS [英] Cant enable CORS on the server side NodeJS

查看:94
本文介绍了无法在服务器端NodeJS上启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在服务器端启用 CORS .我的前端和后端服务器具有不同的端口.这是服务器端的实现方式:

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

然后像这样从前端调用 fetch 函数:

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

但仍然出现错误:

安全错误:http://localhost:3030/上的内容可能无法从http://localhost:3035/加载数据.

TypeError:尝试获取资源时出现网络错误."

推荐答案

您在客户端设置了 mode:'same-origin'而不是显式地不允许在客户端进行CORS默认的模式:'cors'.

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

引用 docs :

same-origin —如果使用此模式设置向另一个来源发出请求,则结果只是一个错误.您可以使用它来确保始终向您的来源发出请求.

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.

由于 http://localhost:3035/ http://localhost:3030/之外的另一个来源,因此,完全符合设计要求,只是一个错误".

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

将其设置为 mode:'cors'或完全删除 mode ,因为 cors 仍然是默认设置.

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

另一方面, Access-Control-Request-Method 是预检请求中的 request 标头,而不是响应标头.您应该将其删除.

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

如评论中所述:为了使凭据请求生效,您不能使用允许的 * 来源.但是,如果您此时不想对预期的原点进行硬编码,则可以通过始终使用 res.setHeader('Access-Control-Allow-Origin',req.headers.origin).

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

这篇关于无法在服务器端NodeJS上启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆