標籤:url tps lock href axios catch str 格式 load
當參數是JSON對象時,預設的Content-Type是application/json。
axios.post(‘/user‘, { firstName: ‘Fred‘, lastName: ‘Flintstone‘ }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
此時傳遞的參數是Request Payload格式{firstName:"Fred",lastName:"Flintstone"}
如果出現No ‘Access-Control-Allow-Origin‘ header is present on the requested resource的錯誤,則是跨域問題。本人喜歡直接設定管理員來解決跨域:例如Nginx配置:Nginx配置跨域請求
當參數是JSON字串時,預設的Content-Type是application/x-www-form-urlencoded。
axios.post(‘/user‘, JSON.stringify({ firstName: ‘Fred‘, lastName: ‘Flintstone‘ })) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
此時傳遞的參數是Form Data格式key : value:
{"firstName":"Fred","lastName":"Flintstone"}:
如上。其實這是一個無效的資料,key為{"firstName":"Fred","lastName":"Flintstone"},value為空白。
要想使用application/x-www-form-urlencoded格式,需要進行資料轉換,雖然有兩種方式URLSearchParams和qs兩種方式。我更喜歡使用qs庫的方式,代碼如下:axios.interceptors.request.use((req) => { if (req.method === ‘post‘) { req.data = qs.stringify(req.data); } return req;}, (error) => Promise.reject(error));
之後使用axios的時候,只需要傳遞json對象就可以:
axios.post(‘/user‘, { firstName: ‘Fred‘, lastName: ‘Flintstone‘ }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
axios請求JSON問題詳解