axios請求JSON問題詳解

來源:互聯網
上載者:User

標籤: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格式,需要進行資料轉換,雖然有兩種方式URLSearchParamsqs兩種方式。我更喜歡使用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問題詳解

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.