簡體   English   中英

API請求無法在Ajax中運行,但可以在POSTMAN中運行

[英]API Request not working in ajax but working in POSTMAN

我試圖用AJAX中的一個參數向本地服務器發出發布請求。 當我在郵遞員中執行請求時,它似乎工作得很好,但是當我使用AJAX執行該請求時,它將發送兩個請求,一個請求為204,另一個請求為404,這看起來很奇怪:

<-- OPTIONS /price/current
api_1       |   --> OPTIONS /price/current 204 1ms 
api_1       |   <-- POST /price/current
api_1       |   --> POST /price/current 404 1ms -

實際的AJAX請求如下:

getBtc = async()  => {
     return await fetch("http://localhost:3001/price/current",{
         method: 'POST',
         headers: {
             'Content-Type':'application/json'

         },
         body: JSON.stringify({
             'symbol':'eth'
         })
     })          
     .then(res => {
         console.log(res)
         if (res.success) {
           this.setState({ priceBTC : res.data[0].price })
         }
     })

控制台日志使用以下信息指定200響應:

Response {type: "cors", url: "http://localhost:3001/price/btc", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:3001/price/btc"
__proto__: Response

理想情況下,我將獲得200的狀態碼

請嘗試以下方法:

.then(res => res.json())
.then(jsonRes => {
    console.log(jsonRes)
    if (jsonRes.success) {
        this.setState({ priceBTC : jsonRes.data[0].price })
    }
 })
.catch(err => {
    alert('Something went wrong')
});

在這里,我們將響應res轉換為json並從中訪問data[]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM