我很難用fetch方法向我的Expressjs后端發送獲取請求。
fetch('http://localhost:9000'/span>, { method: 'GET', headers: { Authorization: `Bearer ${accessToken.accessToken}` }}).then(() => //span> {
debugger。
}).catch((error) =>/span> {
除錯器。
})
根據我所讀到的內容,這似乎是正確的--但是請求沒有到達API。
我試著像這樣構建選項物件,但沒有任何收獲:
我試著像這樣構建選項物件。
span class="hljs-keyword">const options = {
method: "GET"。
headers: headers
};
如果沒有頭資訊,我的請求就能到達API。總之,我得到的錯誤是這樣的:
錯誤。TypeError: 獲取失敗
uj5u.com熱心網友回復:
如果你從http://localhost:9000以外的來源發出該請求,Authorization頭將導致瀏覽器在GET請求之前發出一個CORS預檢請求OPTIONS http://localhost:9000,如果該請求失敗,GET請求將不會被發出。
您必須確保您的服務器處理預檢,例如,通過cors中間件。
uj5u.com熱心網友回復:
所以我找到了一個解決方案,基本上我在我的Express應用程式中添加了這個中間件,以允許CORS,
app.use((req, res, next) => //span> {
res.header("Access-Control-Allow-Origin", "*") 。
res.header("Access-Control-Allow-Headers", "*") 。
res.header("Access-Control-Allow-Methods", "*") 。
next()。
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/310204.html
標籤:
