javascript - 如何在 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 我该如何解决这个问题?
解决方案
CORS 只是浏览器拥有的默认安全机制。MDN 有一个很好的资源。
为了能够让您的 Node API 发送响应,只需添加:
res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000")
前res.end(JSON.stringify(dataExplained))
推荐阅读
- java - 检查点发生时,flink 广播状态不会保存到rocksdb?
- apache-spark - 我们可以将 Spark 的 CBO(基于成本的优化器)与原生 parquet 或内存数据帧结合使用吗?
- prolog - 如何使用 Prolog 解决运输问题?
- math - 两个快速移动的圆圈之间的碰撞解决方案。一种对碰撞没有反应的
- matlab - (MATLAB)如何获得一系列图像的最大和最小背景?
- bash - 如何使用 Xidel 从图像 @srcset 属性中获得图像的最佳分辨率?
- php - 将验证码添加到 formmail pro core.cgi
- css - 如何隐藏 asp:BoundField 与 css
- ms-access - MS Access - 查询运行后添加到查询的条件
- javascript - Javascript:按文件路径比较两个选定的文件