axios 的封装
项目中,在scr目录下建一个名为api 的文件夹。里面需要有两个js文件,分别为 request.js 和 http.js
request.js 中
import axios from 'axios';
axios.defaults.timeout = 30000;
//http request 拦截器
axios.interceptors.request.use(config => {
config.baseURL = process.env.NODE_ENV === "development"?"":"实际地址"
//其他熟悉根据项目实际需要添加
return config;
},
error => {
return Promise.reject(error);
}
);
axios.interceptors.response.use(res => {
//需要的其他操作
return res
}, error => {
console.log('error.response: ', error.response);
console.log('error.message: ', error.message);
if (error.message.includes('timeout')) {
toastError('请求超时,请重试!')
//需要的其他操作
return Promise.reject(error);
}
if (error.response.status == 401) {
//需要的其他操作
return Promise.reject(error);
}
return Promise.reject(error);
})
export default axios
http.js 中
// 导入request
import request from './request'
const http = {
/**
* @param url 请求地址
* @param params 请求参数
*/
get(url, params) {
const config = {
method: 'get',
url: url
}
if (params) {
config.params = params
}
return request(config)
},
post(url, data) {
const config = {
method: 'post',
url: url
}
if (data) config.data = data
return request(config)
},
put(url, params) {
const config = {
method: 'put',
url: url
}
if (params) config.data = params
return request(config)
},
delete(url) {
const config = {
method: 'delete',
url: url
}
return request(config)
},
}
//导出
export default http
之后可以在api文件夹中新建其他文件,来放置对应不同业务的请求。如我在api,新建了一个请求楼层的信息的 building.js ,内容如下:
//引入http
import http from '../http';
let requests = "/building";
// 获取楼宇列表
export function getBuildingList(params) {
//调用http中的方法
return http.get("/building/page", params)
}
这样再在实际的vue文件中引入并且调用就可以了
import { getBuildingList} “@/api/building.js ”
跨域请求的设置
以下都后台对跨域请求进行处理后
vuecli2
在config文件中的index.js 文件中 修改dev 的配置就可以。
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: { //具体请求可以代理多个
'/building': {
target: "xxxxxx",//具体请求的地址如 :'http://192.168.1.1:9999'
changeOrigin: true,
ws: true,
pathRewrite: {
'^/building': '/building'// 说明 '^/building' ,所有和这个字符串匹配的请求,都会被重写为'/building'这个请求。
}
}
}
host: '0.0.0.0', // 修改为0.0.0.0 可以是页面通过内网地址访问,配置成localhost 则不行。
}
这样页面在发送请求的时候,虽然在浏览器中,还是会显示成本地的请求路径,但是实际上请求已经被代理为上面配置的target 加上具体的pathRewrite 重写的路径。
如果对index.js 有修改 必须重启项目才会生效。
以上的写法都是在开发环境中的配置。
vuecli3、4
在vue.config.js ,
devServer:{
proxy: {
'/building': {
target: "xxxxxx",//具体请求的地址如 :'http://192.168.1.1:9999'
changeOrigin: true,
ws: true,
pathRewrite: {
'^/building': '/building'
}
}
}
}