為什麼api總是打兩次?

最近開始寫前端後有點疑問,開chrome的Network起來看api request情況,看他總是打了兩次(如圖),難道是我程式哪裡寫錯了!?

google了下發現,原來是跟CORS機制有關,跨domain就會觸發,當去其他domain要東西(發request),會為了確認先發一次api,確認了沒問題,request被allowed(此時response為204 no content),才會真的打下去~解決了疑惑XD 真的該來好好研究下CORS了,感覺常常被他坑到0.0

Axios 同步

今天串接api覺得奇怪,怎麼console.log沒印東西出來,試打api以後發現get很久,看起來是api response還沒回來程式就結束了orz,之前看axios教學跳過同步這塊,看來遲早要面對的,不能逃避了XD

前公司有遇過jquery ajax的問題,那時候因為案子不做了,就沒有繼續優化這塊,最近寫vue串api是用axios。

axios的介紹參考網路找到的:

What is Axios?

Axios is a modern, Promise-based HTTP client library. This means that Axios is used to send an HTTP request and handle their responses, all using JavaScript’s promises. Axios supports both Node.js and JavaScript in the browser.

原本的寫法是serial query,像是這樣:

methods:{

getXX(){

axios.get(){//do first}

axios.get(){//do after first done}

}

}

加上async的寫法是這樣:

methods:{

getXX(){

const sendGetReq = async()=> {

try{

const resp = await axios.get(){//do first}

axios.get(){//do after first done}

}catch(err){console.log(err)}

};

sendGetReq();

}

}

成功等待api回傳和更新資料了,之後再來研究更好的寫法~~

references:

https://stackabuse.com/making-asynchronous-http-requests-in-javascript-with-axios/