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


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

中文:https://www.kancloud.cn/yunye/axios/234845

github: https://github.com/axios/axios

vue路由文檔:https://router.vuejs.org/zh/

 

一、安裝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);
  });

 

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

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

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

proxyTable:{
     "/api":{
         target:"后端提供服務的前綴地址",
         changeOrigin:true,
         pathRewrite:{
              '^/api':''
         }
     }
},

  第二步(在main.js中添加一個代理)

Vue.prototype.HOST='/api'

 

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

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

  聲明:此種跨域只適用於測試開發階段,項目正式上線並不實用,需要后端去處理跨域問題

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM