Javascript 如何访问我在react.j的localhost node.js中创建的api
我正在尝试使用react.js、node.js和puppeter创建一个新冠病例应用程序。使用node.js和puppeter,我创建了一个api。这是我的节点代码Javascript 如何访问我在react.j的localhost node.js中创建的api,javascript,node.js,reactjs,fetch,puppeteer,Javascript,Node.js,Reactjs,Fetch,Puppeteer,我正在尝试使用react.js、node.js和puppeter创建一个新冠病例应用程序。使用node.js和puppeter,我创建了一个api。这是我的节点代码 const puppeteer = require("puppeteer") var http = require("http") var fs = require("fs") let dataExplained = {} async function getCovidCa
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:8080/api/covid/canada“起源”http://localhost:3000'已被CORS策略阻止:请求的资源上不存在'Access Control Allow Origin'标头。如果不透明响应满足您的需要,请将请求的模式设置为“no cors”,以获取禁用cors的资源。
得到http://localhost:8080/api/covid/canada net::ERR_失败
如何修复此问题?CORS只是浏览器的默认安全机制。MDN有一个 要使您的节点API能够发送响应,只需添加:
res.setHeader(“访问控制允许原点”http://localhost:3000")
在
res.end(JSON.stringify(dataExplained))
之前,CORS只是浏览器的默认安全机制。MDN有一个
要使您的节点API能够发送响应,只需添加:
res.setHeader(“访问控制允许原点”http://localhost:3000")
在
res.end(JSON.stringify(dataExplained))
之前,您是否在API中间件上配置头文件?您可以添加您正在配置的头吗?您正在API中间件上配置头吗?您可以添加您正在配置的标题吗?