简体   繁体   English

如何访问我在 react.j 的本地主机 node.js 中创建的 api

[英]How to access the api I created in localhost node.js in react.j

I am trying to create a covid cases app with react.js, node.js, and puppeteer.我正在尝试使用 react.js、node.js 和 puppeteer 创建一个 covid 案例应用程序。 With node.js and puppeteer I created an api.使用 node.js 和 puppeteer,我创建了一个 api。 This is my code for node.这是我的节点代码。

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

This is the json file it outputs to localhost 8080:这是它输出到 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"}

Then I tried to access that json api file in my react.js file.然后我尝试访问我的 react.js 文件中的 json api 文件。 This is my code:这是我的代码:

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

But it gave me multiple errors: Access to fetch at 'http://localhost:8080/api/covid/canada' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.但它给了我多个错误:CORS 政策阻止了从源“http://localhost:3000”获取“http://localhost:8080/api/covid/canada”的访问权限:没有“访问控制- Allow-Origin' header 存在于请求的资源上。 If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。 GET http://localhost:8080/api/covid/canada net::ERR_FAILED How Do I Fix This? GET http://localhost:8080/api/covid/canada net::ERR_FAILED我该如何解决这个问题?

CORS is just a default security mechanism that browsers have. CORS 只是浏览器具有的默认安全机制。 MDN has a good resource about it . MDN 有一个很好的资源

To be able to your Node API send the response, just add:为了能够向您的节点 API 发送响应,只需添加:

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

before res.end(JSON.stringify(dataExplained))res.end(JSON.stringify(dataExplained))之前

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM