1. 程式人生 > >Vue使用Axios實現http請求以及解決跨域問題

Vue使用Axios實現http請求以及解決跨域問題

Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。Axios的中文文件以及github地址如下:

一、安裝Axios外掛

npm install axios --save

二、在main.js中引入Axios庫

import Axios from "axios"
//將axios掛載到原型上
Vue.prototype.$axios = Axios;

//配置全域性的axios預設值(可選)

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

三、使用get方式的http請求

this.$axios.get("請求url",{param:{}})
           .then(function(response){
                  console.info(response.data);
                 })
           .catch(function(error){
                   console.info(error);
                 });

四、使用post方式的http請求

this.$axios.post("請求路徑",{})
           .then(function(response){
                  console.info(response.data);
                 })
           .catch(function(error){
                  console.info(error);
                 });

注意使用上述post方式提交引數的時候存在問題,axios中post的請求引數格式是form-data格式。而上述json串的格式為x-www-form-urlencoded格式

例如:

form-data:?name="zhangsan"&age=10 

x-www-form-urlencoded:{name:"zhangsan",age:10}

此時我們需要將資料格式作轉換,在當前頁面引入第三方庫qs

import qs from "qs"

此時上述引數改為:

this.$axios.post("請求路徑",qs.stringify({}))
           .then(function(response){
                  console.info(response.data);
                 })
           .catch(function(error){
                  console.info(error);
                 });

五、Axios的攔截器

  攔截器在main.js中進行配置,配置如下:

// 新增請求攔截器
axios.interceptors.request.use(function (config) {
    // 在傳送請求之前做些什麼
    return config;
  }, function (error) {
    // 對請求錯誤做些什麼
    return Promise.reject(error);
  });

// 新增響應攔截器
axios.interceptors.response.use(function (response) {
    // 對響應資料做點什麼
    return response;
  }, function (error) {
    // 對響應錯誤做點什麼
    return Promise.reject(error);
  });

基於以上的攔截器,我們可以對請求的資料或者是響應的資料做些處理,就拿上面post方式的請求引數格式舉個例子,通過攔截器我們可以對所有的post方式的請求引數在發出請求之前作出轉換:

import qs from "qs"


// 新增請求攔截器
axios.interceptors.request.use(function (config) {
    // 引數格式轉換
    if(config.method=="post"){
        config.data = qs.stringify(config.data);
    }
    return config;
  }, function (error) {
    // 對請求錯誤做些什麼
    return Promise.reject(error);
  });

  因此基於攔截器我們在post請求的時候可以直接使用from-data的格式,不需要每次都編碼轉換

 六、前端跨域解決方案(瞭解)

描述:由於使用vue腳手架的目的就是使前後端分離,前端請求後端的資料在測試階段設計到跨域請求問題,在前端中我們可以通過如下配置解決跨域請求問題。

  第一步(在config資料夾下的index.js中進行如下修改)

proxyTable:{
     "/api":{
         target:"後端提供服務的字首地址",
         changeOrigin:true,
         pathRewrite:{
              '^/api':''
         }
     }
},

  第二步(在main.js中新增一個代理)

Vue.prototype.HOST='/api'

 再進行請求的時候只需要使用url = this.HOST+"請求的Mappering地址"即可

(注意:在上述過程中修改了config下的配置檔案,服務需要重新啟動,才能生效)

  宣告:此種跨域只適用於測試開發階段,專案正式上線並不實用,需要後端去處理跨域問題