axios請求JSON問題詳解

  • 當參數是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);
      });
  • 發表評論
    所有評論
    還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
    相關文章