一文帶你了解Vue中的axios和proxy代理
1.引入axios
npm install axios
2.配置proxy代理,解決跨域問題
proxyTable: { "/api": { target: "http://192.168.X.XXX:XXXX", //需要跨域的目標(biāo) pathRewrite: { "^/api": "" }, //將帶有api的路徑重寫為‘' ws: true, //用與支持webCocket changeOrigin: true //用于控制請求頭的Host }, "/two": { target: "http://XXX.XXX.X.XXX:XXXX", pathRewrite: { "^/two": "" }, ws: true, changeOrigin: true } },
3.引入axios,二次封裝,添加請求、響應(yīng)攔截器
import axios from "axios"; const requests = axios.create({//創(chuàng)建 baseURL: "/api", //在調(diào)用路徑中追加前綴‘/api' timeout: 50000 //單位ms,超過該時間即為失敗 }); //添加請求攔截器 requests.interceptors.request.use( function(config) { config.headers.token ="token";//在發(fā)送請求之前的行為,加入token return config; }, function(error) { //處理錯誤請求 return Promise.reject(error); } ); //添加響應(yīng)攔截器 requests.interceptors.response.use( function(response) { //成功接收到響應(yīng)后的行為,例如判斷狀態(tài)碼 return response; }, function(error) { //處理錯誤響應(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="/">回到首頁</router-link></p> <h1>axios測試</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>
控制臺成功調(diào)用:
6.地址變化過程
①實際登錄接口:http://192.168.x.xxx:xxxx/getUser
…中間省略了配置過程…
②npm run serve:Local: http://localhost:8080/
③點擊后發(fā)送的登錄請求:http://localhost:8080/api/getUser
http://localhost:8080會加上'/getUser'=>http://localhost:8080/getUser,因為創(chuàng)建axios時加上了“/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
⑥實際接口當(dāng)中沒有這個api,此時pathwrite重寫就解決這個問題的。
⑦pathwrite識別到api開頭就會把"/api"重寫成空,那就是不存在這個/api了,完整的路徑又變成:http://192.168.x.xxx:xxxx/getUser
到此這篇關(guān)于一文帶你了解Vue中的axios和proxy代理的文章就介紹到這了,更多相關(guān)Vue axios proxy代理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家

vue 不使用select實現(xiàn)下拉框功能(推薦)

vue history 模式打包部署在域名的二級目錄的配置指南

vue2+elementui的el-table固定列會遮住橫向滾動條及錯位問題解決方案