首页 > 解决方案 > 如何在 react.j 中访问我在 localhost node.js 中创建的 api

问题描述

我正在尝试使用 react.js、node.js 和 puppeteer 创建一个 covid 案例应用程序。使用 node.js 和 puppeteer 我创建了一个 api。这是我的节点代码。

const puppeteer = require("puppeteer")
var http = require("http")
var fs = require("fs")
let dataExplained = {}
async function getCovidCases(){
    const browser = await puppeteer.launch()
    const page = await browser.newPage()
    const url = "https://www.worldometers.info/coronavirus/#countries"
    await page.goto(url, {waitUntil: 'networkidle0'})
    const results = await page.$$eval(".even", navBars => {
        return navBars.map(navBar => {
          const anchors = Array.from(navBar.getElementsByTagName('td'));
          return anchors.map(anchor => anchor.innerText);
        });
      })
      browser.close()
      dataExplained.country = results[15][1]
      dataExplained.totalCases = results[15][2]
      dataExplained.newCases    = results[15][3]
      dataExplained.totalDeaths    = results[15][4]
      dataExplained.newDeaths    = results[15][5]
      dataExplained.totalRecovered    = results[15][6]
      dataExplained.activeCases    = results[15][7]
      dataExplained.critical    = results[15][8]
      dataExplained.totalCasesPerMillion    = results[15][9]
      dataExplained.deathsPerMillion    = results[15][10]
      dataExplained.totalTests    = results[15][11]
      dataExplained.totalTestsPerMillion    = results[15][12]
      dataExplained.population = results[15][13]
      var server = http.createServer((req, res) => {
        if (req.url === "/api/covid/canada"){
          res.writeHead(200, {"Content-Type": "application/json"})
          res.end(JSON.stringify(dataExplained))
        }
      })
      server.listen(8080, "127.0.0.1")
      console.log("wooh sent")
}
getCovidCases()

这是它输出到 localhost 8080 的 json 文件:

{"country":"Canada","totalCases":"582,697","newCases":"+1,302","totalDeaths":"15,606","newDeaths":"","totalRecovered":"489,819","activeCases":"77,272","critical":"711","totalCasesPerMillion":"15,371","deathsPerMillion":"412","totalTests":"13,775,115","totalTestsPerMillion":"363,376","population":"37,908,690"}

然后我尝试在我的 react.js 文件中访问该 json api 文件。这是我的代码:

  fetch("http://localhost:8080/api/covid/canada")
  .then(req => req.json())
  .then(myJson => console.log(myJson)

但这给了我多个错误:CORS 策略阻止了从源“http://localhost:3000”获取“http://localhost:8080/api/covid/canada”的访问权限:没有“访问控制-请求的资源上存在 Allow-Origin' 标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。GET http://localhost:8080/api/covid/canada net::ERR_FAILED 我该如何解决这个问题?

标签: javascriptnode.jsreactjsfetchpuppeteer

解决方案


CORS 只是浏览器拥有的默认安全机制。MDN 有一个很好的资源

为了能够让您的 Node API 发送响应,只需添加:

res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000")

res.end(JSON.stringify(dataExplained))


推荐阅读