博客 / 詳情

返回

[axios] axios中get請求的發送

"Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests."

—https://axios-http.com/docs/intro

Axios是一個基於Promise的node.js和瀏覽器的HTTP客户端。它是同構的(即可以在瀏覽器和node.js中使用相同的代碼庫)。在服務器端,它使用原生的node.js http模塊,而在客户端(瀏覽器)則使用XMLHttpRequests。

對於發送get請求,axios中可以有下面幾種方式:

1、axios(config) (建議使用)
舉例:

axios({
  method: 'get',
  url: '/fund/info',
  params: {
    fundId: "000001",
    type: "bond"
  }
});

2、axios(url) || axios(url[, config]) (不建議使用)
説明:未指定方法,請求將默認為GET方法。
舉例:

axios('/user/info');
axios('/management/doc', {
  responseType: "blob",
  timeout: 8000,
  params: {
      id: "abc123"
  }
});

3、axios.get(url) || axios.get(url[, config]) (建議使用)
舉例:

axios.get('/fund/basicInfo', {
  params: {
      fundId: "abc123"
  }
});

4、axios.request(config) (不建議使用)
舉例:

axios.request({
  method: 'get',
  url: "/management/doc"
  responseType: "blob",
  timeout: 8000,
      params: {
      id: "abc123"
  }
});

以上四種方式都是可行的,建議在1、3中選擇一種,最好項目整體都選用同一種,保持一致性。

上面各種方式的params最終都會變成url中的query參數

例如:

axios.get('/fund/info, {
  params: {
      fundId: "000001",
      type: "bond"
  }
});

最終發送的請求是 /fund/info?fundId=abc123&type=bond

在params中key存在,但value為null或undefined的參數不會在URL中顯示。
例如:

axios.get('/fund/info, {
  params: {
      fundId: "000001",
      type: undefined
  }
});

最終發送的請求是 /fund/info?fundId=abc123

同步更新到自己的語雀
https://www.yuque.com/dirackeeko/blog/dnlygqwhft5qr1rm

user avatar heptagon 頭像 alogy 頭像 nidexiaoxiongruantangna 頭像 anetin 頭像 hs_developer 頭像 lixiang314 頭像 u_16099196 頭像 qingtianwoniu 頭像
8 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.