一文帶你了解Vue中的axios和proxy代理
1.引入axios
npm install axios
2.配置proxy代理,解決跨域問(wèn)題
proxyTable: {
"/api": {
target: "http://192.168.X.XXX:XXXX", //需要跨域的目標(biāo)
pathRewrite: { "^/api": "" }, //將帶有api的路徑重寫為‘'
ws: true, //用與支持webCocket
changeOrigin: true //用于控制請(qǐng)求頭的Host
},
"/two": {
target: "http://XXX.XXX.X.XXX:XXXX",
pathRewrite: { "^/two": "" },
ws: true,
changeOrigin: true
}
},
3.引入axios,二次封裝,添加請(qǐng)求、響應(yīng)攔截器
import axios from "axios";
const requests = axios.create({//創(chuàng)建
baseURL: "/api", //在調(diào)用路徑中追加前綴‘/api'
timeout: 50000 //單位ms,超過(guò)該時(shí)間即為失敗
});
//添加請(qǐng)求攔截器
requests.interceptors.request.use(
function(config) {
config.headers.token ="token";//在發(fā)送請(qǐng)求之前的行為,加入token
return config;
},
function(error) {
//處理錯(cuò)誤請(qǐng)求
return Promise.reject(error);
}
);
//添加響應(yīng)攔截器
requests.interceptors.response.use(
function(response) {
//成功接收到響應(yīng)后的行為,例如判斷狀態(tài)碼
return response;
},
function(error) {
//處理錯(cuò)誤響應(yīng)
return error;
}
);
export default requests;
4.封裝接口調(diào)用
import request from "./request";
export function getData(){
return request({
url:'/getUser',//
method:'get'
})
}
5.vue中調(diào)用接口
<template>
<div>
<p><router-link to="/">回到首頁(yè)</router-link></p>
<h1>axios測(cè)試</h1>
</div>
</template>
<script>
import {getData} from "@/api/index.js"
export default {
data() {
return {}
},
mounted(){
console.log("開始了")
this.fetchData()
},
methods:{
async fetchData(){
let result = await getData()
console.log(result)
}
}
}
</script>
<style scoped>
</style>
控制臺(tái)成功調(diào)用:


6.地址變化過(guò)程
①實(shí)際登錄接口:http://192.168.x.xxx:xxxx/getUser
…中間省略了配置過(guò)程…
②npm run serve:Local: http://localhost:8080/
③點(diǎn)擊后發(fā)送的登錄請(qǐng)求:http://localhost:8080/api/getUser
http://localhost:8080會(huì)加上'/getUser'=>http://localhost:8080/getUser,因?yàn)閯?chuàng)建axios時(shí)加上了“/api前綴”=》http://localhost:8080/api/getUser
④代理中“/api” 的作用就是將/api前的"localhost:8080"變成target的內(nèi)容http://192.168.x.xxx:xxxx/
⑤完整的路徑變成了http://192.168.x.xxx:xxxx/api/getUser
⑥實(shí)際接口當(dāng)中沒有這個(gè)api,此時(shí)pathwrite重寫就解決這個(gè)問(wèn)題的。
⑦pathwrite識(shí)別到api開頭就會(huì)把"/api"重寫成空,那就是不存在這個(gè)/api了,完整的路徑又變成:http://192.168.x.xxx:xxxx/getUser
到此這篇關(guān)于一文帶你了解Vue中的axios和proxy代理的文章就介紹到這了,更多相關(guān)Vue axios proxy代理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家
相關(guān)文章
vue?vue-touch移動(dòng)端手勢(shì)詳解
這篇文章主要介紹了vue?vue-touch移動(dòng)端手勢(shì)詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
vue 不使用select實(shí)現(xiàn)下拉框功能(推薦)
Vue高級(jí)用法實(shí)例教程之動(dòng)態(tài)組件
Vue input輸入框中的值如何變成黑點(diǎn)問(wèn)題
vue history 模式打包部署在域名的二級(jí)目錄的配置指南
vue2+elementui的el-table固定列會(huì)遮住橫向滾動(dòng)條及錯(cuò)位問(wèn)題解決方案

