微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何访问我在 localhost node.js 中创建的 api react.j

如何解决如何访问我在 localhost node.js 中创建的 api react.j

我正在尝试使用 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)

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

解决方法

CORS 只是浏览器具有的默认安全机制。 MDN 有一个 good resource about it

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。