提问者:小点点

无法在服务器端节点上启用CORS


我无法在服务器端启用cors。 我的前端和后端服务器有不同的端口。 以下是服务器端的实现方式:

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函数,如下所示:

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:“尝试提取资源时出现NetworkError.”


共1个答案

匿名用户

您通过设置模式:'same-origin'而不是默认的模式:'CORS'显式禁止在客户端使用CORS。

要引用文档:

some-origin-如果使用此模式设置向另一个源发出请求,结果只是一个错误。 您可以使用这一点来确保始终向您的源发出请求。

由于http://localhost:3035/http://localhost:3030/之外的另一个起源,因此结果与设计完全一样,“只是一个错误”。

将其设置为模式:'cors'或完全删除模式,因为cors无论如何都是默认的。

另外,access-control-request-method是预飞行请求中的请求头,而不是响应头。 你应该移除它。

正如注释中提到的:要使一个凭据请求工作,您不能使用允许的*起源。 如果您不想在此时硬编码预期的源,可以使用res.setheader('access-control-allow-origin',req.headers.origin)始终返回当前请求所来自的源来避免这个问题。