[英]Unable to fetch JSON from Express server using Fetch api
在端口 8080 上運行的 Express 服務器中,我有;
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8081");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
來自 8081 端口的請求
fetch('http://localhost:8080/...')
.then((response) => response.json())
.then((json) => {
let jsonStr = JSON.stringify(json);
console.log(jsonStr)
})
.catch((error) => console.log(error))
我得到的錯誤:
Access to fetch at 'http://localhost:8080/...' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
如果我只是在瀏覽器上手動輸入 express url,我會看到我試圖獲取的 JSON。
我已經閱讀了多個帖子來解決這個問題,但我似乎仍然無法解決它。
我應該如何獲取以避免此錯誤?
您正在從不同的端口 (8081) 獲取數據,這就是您收到 CORS 錯誤消息的原因。 更改訪問控制策略如下:
res.header("Access-Control-Allow-Origin", "http://localhost:*");
這個鏈接可以派上用場。
您可以使用cors
來擺脫這種情況;
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.