vue+axios拦截器+webpcak跨域代理,axios自定义封装,加入拦截器便于统一管理例如页面loading效果。
首先看一下我的项目目录结构,基础版还未完善,大佬勿嫌
项目目录
在request.js文件中引入axios,qs(qs为了处理请求格式问题,依照项目需要,此处不细说),我在自定义axios请求头中加入了token,值存放于vuex模块A中管理,所以也引入了store来获取这个token值。(vuex分模块管理状态后面文章细说,我也知道个常用的而已)
讲一下这个baseURL的api,这里的api是我们在config文件下index.js里面设置的跨域代理proxyTable中定义好的api。
在页面最底部export 导出自定义的axios,便于fitch.js页面引入
import axios from 'axios'
import qs from 'qs'
import store from '../vuex'
//封装axios
const instance = axios.create({
baseURL: 'api',
withCredentials: true,//是否携带cookie信息
timeout: 1000,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
//设置token,token存储在vuex的moduleA中
instance.defaults.headers.common['Authorization'] = store.state.a.token
//headers的另一种格式 'application/json'
/****** request拦截器==>对请求参数做处理 ******/
instance.interceptors.request.use(config => {
config.method === 'post'
? config.data = qs.stringify({...config.data})
: config.params = {...config.params};
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
return config;
}, error => { //请求错误处理
Promise.reject(error)
});
/****** respone拦截器==>对响应做处理 ******/
instance.interceptors.response.use(
response => { //成功请求到数据
//这里根据后端提供的数据进行对应的处理
if (response.data.message === 'success') {
console.log(response)
return response;
} else {
//常规错误处理
}
},
error => { //响应错误处理
console.log('error');
console.log(error);
console.log(JSON.stringify(error));
return Promise.reject(error)
}
)
export default instance
在fitch.js文件中引入封装好的axios(拦截器),这里的fitch.js文件相当于业务请求,建议不同的业务放于不同文件,便于后期分类管理维护
import instance from './request'
//测试跨域代理get
function searchBank(params){
return instance({
url: '/QXTrain/train_questionbank',
method: 'get',
params
})
// let par = params;
// return instance.get( '/QXTrain/train_questionbank', {params:par},{headers: {'Content-Type':'application/json'}});
}
//测试跨域代理post
function editBank(data){
return instance({
url: '/QXTrain/train_questionbank_upd',
method: 'post',
data
})
// let par = params;
// return instance.post( '/QXTrain/train_questionbank_upd', par);
}
export {searchBank,editBank}
最后看一下config下index.js中的代码,有设置的跨域代理api,和request.js中设置baseURL的api是一致的,只要看proxyTable里面,其他可以忽略。
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': { // api相当于一个别名,代指 http://221.241.138.173:5018
'target':'http://221.241.138.173:5018',
'changeOrigin':true,
'pathRewrite': {
'^/api':''
}
}
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: true,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
// Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: true,
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false,
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}
采用这个api代理,后面项目接口公用地址修改,只需要修改这一处即可。