[英]How to access the api I created in localhost node.js in 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)
但它給了我多個錯誤:CORS 政策阻止了從源“http://localhost:3000”獲取“http://localhost:8080/api/covid/canada”的訪問權限:沒有“訪問控制- Allow-Origin' header 存在於請求的資源上。 如果不透明的響應滿足您的需求,請將請求的模式設置為“no-cors”以獲取禁用 CORS 的資源。 GET http://localhost:8080/api/covid/canada net::ERR_FAILED我該如何解決這個問題?
CORS 只是瀏覽器具有的默認安全機制。 MDN 有一個很好的資源。
為了能夠向您的節點 API 發送響應,只需添加:
res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000")
在res.end(JSON.stringify(dataExplained))
之前
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.