1. 程式人生 > 實用技巧 >axios相關使用記錄

axios相關使用記錄

axios相關使用

一、axios安裝

  • 使用npm安裝axios
npm install axios
  • 使用cnpm安裝axios
 cnpm install axios
  • 使用yarn安裝axios
yarn install axios
  • 使用cdn連結axios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

二、請求資料方法

  • get請求:方式一:
    axios({
        // 預設請求方式為get
        method: 'get',
        url: 
'api', // 傳遞引數 params: { key: value }, // 設定請求頭資訊 headers: { key: value } responseType: 'json' }).then(response => { // 請求成功 let res = response.data; console.log(res); }).catch(error => {
// 請求失敗, console.log(error); });
  • get請求:方式二
    axios.get("api", {
        // 傳遞引數
        params: {
            key: value
        },
        // 設定請求頭資訊,可以傳遞空值
        headers: {
            key: value
        }
    }).then(response => {
        // 請求成功
        let res = response.data;
        console.log(res);
    }).
catch(error => { // 請求失敗, console.log(error); });

  • post請求:方式一
    // 注:post請求方法有的要求引數格式為formdata格式,此時需要藉助 Qs.stringify()方法將物件轉換為字串
    let obj = qs.stringify({
        key: value
    });
    
    axios({
        method: 'post',
        url: 'api',
        // 傳遞引數
        data: obj,
        // 設定請求頭資訊
        headers: {
            key: value
        }
        responseType: 'json'
    }).then(response => {
        // 請求成功
        let res = response.data;
        console.log(res);
    }).catch(error => {
        // 請求失敗,
        console.log(error);
    });
  • post請求:方式二
    let data = {
            key: value
           },
            headers = {
                USERID: "",
                TOKEN: ""
          };
    // 若無headers資訊時,可傳空物件佔用引數位置
    axios.post("api", qs.stringify(data), {
                headers
    }
    }).then(response => {
        // 請求成功
        let res = response.data;
        console.log(res);
    }).catch(error => {
        // 請求失敗,
        console.log(error);
    });
  • Qs的使用
    • 引用cdn或者使用npmcnpm或者yarn進行外掛安裝
    • 使用cdn時,預設全域性變數為Qs
    • Qs基本方法使用
      • qs.stringify()方法:將目標資料轉換為string字串
      • qs.parse()方法:將物件字串格式的資料轉換為物件格式

三、相關檔案

資料格式轉換檔案:Qs.js檔案下載

網路資料請求檔案:Axios.js檔案下載

表單校驗檔案:jQuery.validate.min.js檔案下載

以上是基本使用,現在介紹一些其他的注意事項和官方示例

axios使用post提交方式

進行post提交時 1.需要進行序列化轉換 //FormData方式 (預設是這種方式) //axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded;charset=UTF-8'; 2..直接提交json格式不用使用qs進行序列化轉換。(後端也要修改為接收json格式)
//RequestPayload方式(不用QS轉) axios.defaults.headers.post['Content-Type']='application/json'; 3.

qs可通過npm install qs命令進行安裝,是一個npm倉庫所管理的包。

而qs.stringify()將物件 序列化成URL的形式,以&進行拼接。

JSON是正常型別的JSON,請對比一下輸出

var a = {name:'hehe',age:10};
 qs.stringify(a)
// 'name=hehe&age=10'
JSON.stringify(a)
// '{"name":"hehe","age":10}'
leturl='id=1&name=chenchen'qs.parse(url)// {id:1,name:chenchen}

<script>
            
            // 一般引入qs庫都賦值為qs,不過瀏覽器全域性引入的是 window.Qs物件,
            // 所以直接用 qs.stringify() 會報 qs undefined
            var qs = Qs 
            // 配置post的請求頭
            axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
            // qs.stringify() 這裡可以做一下封裝
            axios.post('url', qs.stringify({
                id: 1,
                name: 'zhangsan'
            })).then(function(res) {
                // 返回 Promise物件資料
            })
        </script>

需要注意的是,get和post請求中,params和data容易混淆,這裡官方給出以下解釋:

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

請求配置config:

所以需要注意的是 get 請求其實是兩個引數的一個是 url 和 config,這裡的params是即將與請求一起傳送的 URL 引數,必須是一個無格式物件(plain object)或 URLSearchParams 物件

post 請求是三個引數的一個是url 、data 和 config,而 data是作為請求主體被髮送的資料,只適用於這些請求方法 'PUT', 'POST', 和 'PATCH'瀏覽器專屬:FormData, File, Blob

其他網站介紹的axios基本使用

axios公共url

1.公共url配置

axios.defaults.baseURL="http://127.0.0.1:8888/api/private/v1/"

2.先引入axios

在全域性的main.js中引入axios,之後對公共的urll進行配置,在vue的原型上定義一個屬性,等於這個axios,因為元件都繼承Vue原型物件,所以在任意元件使用this.$http就相當於使用了axios

import axios from "axios"
axios.defaults.baseURL="http://127.0.0.1:8888/api/private/v1/"
Vue.prototype.$http=axios
  const {data:res} =await this.$http.post("login",this.loginForm)

3.使用async

應為axios返回的是一個promise,因此這裡可以使用async函式去簡化它

 loginHandle(){
      this.$refs.loginFormRef.validate(async valid=>{
         if(!valid) return;
        //  console.log(this.$http);
       const {data:res} =await this.$http.post("login",this.loginForm)
         if(res.meta.status !==200){
           console.log("登陸失敗");
         }
       
      })
    }

axios配置

在使用axios的時候需要進行配置

1.配置所有請求的根路徑

axios.defaults.baseURL = 'http://localhost:3000/';

2.配置post請求的content-type

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

3.請求的時候自動攜帶cookie

axios.defaults.withCredentials = true;

get請求

                axios.get('/api/getnewslist', {
                  //params裡面放的是引數
                  params: {}
                }).then((res) => {
                  console.log(res)
                }).catch(function(error){
                  console.log(error)
                })

post請求

 axios.post('api/news/new', {
              //這裡傳遞的是需要傳遞到後臺的資料
                name: '李寧',
                id: '1001'
            })
                .then(function (response) {
                console.log(response.data);
            })
                .catch(function (error) {
                console.log(error);
            });

axios的簡單封裝

import axios from "axios";

const instance=axios.create({
    //這裡是介面公共的url部分,會拼接在url引數前面
    baseURL:"https://api-hmugo-web.itheima.net/api/public/v1",
    timeout:5000,
  
})
export function get(url,params){
    return  instance.get(url,{
        params
    });
}

export function post(url,data){
    return  instance.post(url,data);
}

export function del(url){
    return instance.get(url);
}

export function put(url,data){
    return  instance.put(url,data);
}

axios全域性攔截

1.請求攔截

所有的網路請求都會先走這個方法,我們可以在它裡面為請求新增一些自定義的內容

instance.interceptors.request.use(
    function(config){
        console.group("全域性請求攔截");
        console.log(config);
        console.groupEnd()
        //config.headers.token="1234"
        return config;
    },
    function(err){
        return Promise.reject(err)
    }
)

2.響應攔截

所有的網路請求返回資料之後都會執行此方法,這裡可以根據伺服器放回的狀態碼做相應的處理

instance.interceptors.response.use(
    function(response){
        console.group("全域性響應攔截");
        console.log(response);
        console.groupEnd()
        return response;
    },
    function(err){
        return Promise.reject(err)
    }
)

axios解決跨域

1.跨域問題的描述

當一個域向另外一個域傳送請求時,協議,主機,埠只要又任意一個不同,都會造成跨域問題,只針對於瀏覽器向伺服器傳送請求。

2.解決跨域

1.在vue.config.js中配置代理

 devServer: {
    open: true,
    host: '127.0.0.1',
    port: 3000,
    https: false,
    hotOnly: false,
    proxy: {
        //凡是請求以api開頭的都會使用下面的代理伺服器
        '/api/*': {
          target: 'http://localhost:8899/', // 目標伺服器地址
          secure: false,                    // 目標伺服器地址是否是安全協議
          changeOrigin: true,               // 是否修改來源, 為true時會讓目標伺服器以為是webpack-dev-server發出的請求!服務端和服務端的請求是沒有跨域的
          //pathRewrite: {'^/api': '/'}     // 將/api開頭的請求地址, /api 改為 /, 即 /api/xx 改為 /xx
        }
    }
},
2.解決跨域原理 這裡的解決方式,實際上是將請求傳送給webpack本地配置的一個除錯伺服器dev--serve,在dev--serve配置一個代理,作用是凡是請求以api開頭的都會使用下面的代理伺服器。然後這個dev--serve會向node伺服器傳送請求(這裡的api根據不同的地址不一樣,這裡是api),最後node伺服器會將結果返回給這個dev--serve,dev--serve再將結果返回給瀏覽器。

以上參考網站:https://www.yuque.com/qiannianshiguangliubuxiashunjiandejiyi/pom0qm/qk0qsq

官方api:

axios API

可以通過向axios傳遞相關配置來建立請求

axios(config)
// 傳送 POST 請求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
// 獲取遠端圖片
axios({
  method:'get',
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
})
  .then(function(response) {
  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});

請求方法的別名

為方便起見,為所有支援的請求方法提供了別名
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

注意:

在使用別名方法時,urlmethoddata這些屬性都不必在配置中指定。

建立例項

可以使用自定義配置新建一個 axios 例項

axios.create([config])
const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

例項方法

以下是可用的例項方法。指定的配置將與例項的配置合併。

axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])

請求配置

這些是建立請求時可以用的配置選項。只有url是必需的。如果沒有指定method,請求將預設使用get方法。
{
   // `url` 是用於請求的伺服器 URL
  url: '/user',

  // `method` 是建立請求時使用的方法
  method: 'get', // default

  // `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。
  // 它可以通過設定一個 `baseURL` 便於為 axios 例項的方法傳遞相對 URL
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` 允許在向伺服器傳送前,修改請求資料
  // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法
  // 後面陣列中的函式必須返回一個字串,或 ArrayBuffer,或 Stream
  transformRequest: [function (data, headers) {
    // 對 data 進行任意轉換處理
    return data;
  }],

  // `transformResponse` 在傳遞給 then/catch 前,允許修改響應資料
  transformResponse: [function (data) {
    // 對 data 進行任意轉換處理
    return data;
  }],

  // `headers` 是即將被髮送的自定義請求頭
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` 是即將與請求一起傳送的 URL 引數
  // 必須是一個無格式物件(plain object)或 URLSearchParams 物件
  params: {
    ID: 12345
  },

   // `paramsSerializer` 是一個負責 `params` 序列化的函式
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` 是作為請求主體被髮送的資料
  // 只適用於這些請求方法 'PUT', 'POST', 和 'PATCH'
  // 在沒有設定 `transformRequest` 時,必須是以下型別之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 瀏覽器專屬:FormData, File, Blob
  // - Node 專屬: Stream
  data: {
    firstName: 'Fred'
  },

  // `timeout` 指定請求超時的毫秒數(0 表示無超時時間)
  // 如果請求話費了超過 `timeout` 的時間,請求將被中斷
  timeout: 1000,

   // `withCredentials` 表示跨域請求時是否需要使用憑證
  withCredentials: false, // default

  // `adapter` 允許自定義處理請求,以使測試更輕鬆
  // 返回一個 promise 並應用一個有效的響應 (查閱 [response docs](#response-api)).
  adapter: function (config) {
    /* ... */
  },

 // `auth` 表示應該使用 HTTP 基礎驗證,並提供憑據
  // 這將設定一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設定的自定義 `Authorization`頭
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

   // `responseType` 表示伺服器響應的資料型別,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default

  // `responseEncoding` indicates encoding to use for decoding responses
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default

   // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

   // `onUploadProgress` 允許為上傳處理進度事件
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `onDownloadProgress` 允許為下載處理進度事件
  onDownloadProgress: function (progressEvent) {
    // 對原生進度事件的處理
  },

   // `maxContentLength` 定義允許的響應內容的最大尺寸
  maxContentLength: 2000,

  // `validateStatus` 定義對於給定的HTTP 響應狀態碼是 resolve 或 reject  promise 。如果 `validateStatus` 返回 `true` (或者設定為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` 定義在 node.js 中 follow 的最大重定向數目
  // 如果設定為0,將不會 follow 任何重定向
  maxRedirects: 5, // default

  // `socketPath` defines a UNIX Socket to be used in node.js.
  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  // Only either `socketPath` or `proxy` can be specified.
  // If both are specified, `socketPath` is used.
  socketPath: null, // default

  // `httpAgent` 和 `httpsAgent` 分別在 node.js 中用於定義在執行 http 和 https 時使用的自定義代理。允許像這樣配置選項:
  // `keepAlive` 預設沒有啟用
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' 定義代理伺服器的主機名稱和埠
  // `auth` 表示 HTTP 基礎驗證應當用於連線代理,並提供憑據
  // 這將會設定一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設定的自定義 `Proxy-Authorization` 頭。
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` 指定用於取消請求的 cancel token
  // (檢視後面的 Cancellation 這節瞭解更多)
  cancelToken: new CancelToken(function (cancel) {
  })
}

響應結構

某個請求的響應包含以下資訊

{
  // `data` 由伺服器提供的響應
  data: {},

  // `status` 來自伺服器響應的 HTTP 狀態碼
  status: 200,

  // `statusText` 來自伺服器響應的 HTTP 狀態資訊
  statusText: 'OK',

  // `headers` 伺服器響應的頭
  headers: {},

   // `config` 是為請求提供的配置資訊
  config: {},
 // 'request'
  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}

官方API網址:http://www.axios-js.com/zh-cn/docs/