[英]Fetch problem with node.js express server
我在使用 fetch 和 node.js 時遇到了一些問題。 在我的前端,當我單擊一個按鈕時,我想發送一個發布請求,以便從我的后端接收一個數組作為答案。 我在我的后端使用 node.js 和 express,在我的前端我使用 fetch 函數。
發生的錯誤如下:
CORS 策略已阻止從源“真實本地主機地址”獲取“http://localhost:8080/api”的訪問權限:請求的資源上不存在“Access-Control-Allow-Origin”標頭。 如果不透明的響應滿足您的需求,請將請求的模式設置為“no-cors”以獲取禁用 CORS 的資源。
代碼在這里
const getArray = async() => {
const data = await fetch ("http://localhost:8080/api");
const dataJson = await data.json();
console.log(dataJson)
}
getArray();
在我的服務器中,我有
app.post("/api", (req,res) => {
res.sendFile(JSON.stringify(arr));
});
您需要添加請求選項。 請參閱MDN文檔以獲取更多信息。
正如@Kudah 所說,您應該閱讀文檔。
Fetch(和 XMLHttpRequest)遵循同源策略。 這意味着瀏覽器會限制來自腳本的跨域 HTTP 請求。 當一個域(例如http://example2.com/ )從另一個域(例如http://example1.com/ )請求資源時,就會發生跨域請求。
解決這個問題的最簡單方法,(如果你不想深入研究這個)
const whiteList = [ "https://myRealBackendUrl-1", "https://myRealBackendUrl-2" ];
// you can also pass a string here instead here instead of array
const corsOptions = {
credentials: true,
origin: process.env.NODE_ENV !== production ? "http://localhost:4000" : whiteList
// if you are in a dev environment, you probably want something like localhost
// http://localhost:4000 is just a demo backend. replace it with your own.
// if you are in a production environment, for example heroku then your backend
// url will be something like http://example.herokuapp.com
// in that case `const whiteList = [ "http://example.herokuapp.com" ];`
};
app.use(cors(corsOptions));
上面的代碼對於正常的用例應該足夠了。
還有回調函數,如果你想運行你自己的一些函數。 如果您不打算使用任何動態檢查,請不要閱讀它
var corsOptionsDelegate = async (req, callback) => {
var corsOptions = { origin: false };
try {
// you can do some dynamic check here
// For example: check database for some conditions then allow access
if( myDatabaseSays == true ) corsOptions.origin = true;
else corsOptions.origin = false;
} catch (err) {
console.log(err);
// corsOptions.origin = false;
}
callback(null, corsOptions) // chain it
}
無論如何,請正確閱讀文檔以獲取更多信息 [1]: https ://expressjs.com/en/resources/middleware/cors.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.