簡體   English   中英

將jQuery請求轉換為Axios

[英]Converting jQuery Request to Axios

我有一個用jQuery編寫的應用程序。 我正在努力使其現代化。 作為其中的一部分,我正在嘗試將jQuery請求轉換為Axios。 我的jQuery請求如下所示:

var myUrl = '[someUrl]';
var myData = {
  firstName: 'Joe',
  lastName: 'Smith'
};

$.ajax({
  type: 'POST', url: myUrl, cache: 'false',
  contentType:'application/json',
  headers: {
    'Content-Type': 'application/json',
    'key': '12345'
  },
  data: JSON.stringify(myData),
  success: onSearchSuccess,
  error: onSearchFailure,
  complete: onSearchComplete
}); 

現在,通過我的現代代碼,我有以下內容:

var myUrl = '[someUrl]';
var myData = {
  firstName: 'Joe',
  lastName: 'Smith'
};
axios.post(myUrl, myData)
  .then(function (response) {
    alert('yeah!');
    console.log(response);
  })
  .catch(function (error) {
    alert('oops');
    console.log(error);
  })
;

我不知道如何傳入標題或者我是否需要對myData進行字符串化。 有人可以指點我正確的方向嗎?

你試過這本手冊嗎? :)

這就是你需要的:

axios.post(url [,data [,config]])

將其轉換為代碼的方式是:

var myUrl = '[someUrl]';
var myData = {
  firstName: 'Joe',
  lastName: 'Smith'
};
axios.post(myUrl, myData, {
    headers: {
      'Content-Type': 'application/json',
      'key': '12345'
    }
    // other configuration there
  })
  .then(function (response) {
    alert('yeah!');
    console.log(response);
  })
  .catch(function (error) {
    alert('oops');
    console.log(error);
  })
;

返回的對象實現A + Promise API 根據您的配置,您可能需要對其進行填充,但npm注冊表中有許多可用的包。

暫無
暫無

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

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