![](/img/trans.png)
[英]The flask api endpoint returns the correct response with postman but not with the browser(chrome)
[英]REST API endpoint returns no response with axios in react, but works fine in browser
I created a simple REST API with express and bodyParser which returns a json object on a GET request to the base url. 在瀏覽器中工作正常並返回預期的結果:
API 端點: https://jk9j0.sse.codesandbox.io/ 。
代碼: https://codesandbox.io/s/magical-montalcini-jk9j0
然后我設置一個基本的反應應用程序來使用這個 API,方法是發送一個帶有 axios 的 GET 請求。 但是在調用上面的 API 端點時,我沒有得到任何回應。 試圖捕捉error.request
object,我沒有在標題中看到任何明顯不正確的內容。 error
object 本身顯示“網絡錯誤”。 不知道為什么,當 API 在瀏覽器中按預期工作時。
注意:當我將我的 API url 替換為另一個,預計會發送類似的響應時,一切正常。 The one that works: https://jsonplaceholder.typicode.com/posts/ I haven't created that one, but used it to model my json object.
反應代碼: https://codesandbox.io/s/hungry-sun-rq94r
我嘗試從多個角度進行調查,但沒有運氣。 我在這里想念什么? 我需要在請求中設置一些標頭嗎? 這是 CORS 問題嗎?
是的,原來是 CORS 問題。 在發送響應之前,必須在 API 端點中應用 header。 res.header("Access-Control-Allow-Origin", "*")
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.