簡體   English   中英

無法在服務器端 NodeJS 上啟用 CORS

[英]Cant enable CORS on the server side NodeJS

我無法在服務器端啟用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 function,如下所示:

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

但仍然出現錯誤:

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

TypeError: "NetworkError when attempting to fetch resource."

您通過設置mode: 'same-origin'而不是默認mode: 'cors'在客戶端明確禁止CORS 。

引用 文檔

same-origin — 如果向具有此模式集的另一個源發出請求,則結果只是一個錯誤。 您可以使用它來確保始終向您的來源發出請求。

由於http://localhost:3035/http://localhost:3030/之外的另一個來源,因此結果完全符合設計,“只是一個錯誤”。

將其設置為mode: 'cors'或完全刪除mode ,因為cors無論如何都是默認設置。


附帶說明, Access-Control-Request-Method是預檢請求中的請求header,而不是響應 header。 你應該刪除它。


正如評論中提到的:要使有憑據的請求起作用,您不能使用允許的*來源。 如果您此時不想硬編碼預期的來源,您可以通過始終返回當前請求的來源來避免此問題,使用res.setHeader('Access-Control-Allow-Origin', req.headers.origin)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM