vue-cli3.x 配置代理,封装axios
vue-cli3.x也发布有一段时间了。首先是目录的更改。新增vue.config.js。配置代理在项目根目录下新建vue.config.jsmodule.exports = {devServer: {open: true, //浏览器自动打开页面proxy: {'/api': {target...
·
vue-cli3.x也发布有一段时间了。
首先是目录的更改。新增vue.config.js。
配置代理
在项目根目录下新建vue.config.js
module.exports = {
devServer: {
host:"localhost",//要设置当前访问的ip 否则失效
open: true, //浏览器自动打开页面
proxy: {
'/api': {
target: '目标网址',
ws: true,
changeOrigin: true,
pathRewrite:{
'^/api':''
}
}
}
}
}
这样配置就完成了。
封装axios
配合代理使用
首先,根目录创建一个httpClient目录
config目录下新建axios.js,index.js,interceptors.js,urlconfig.js
axios.js
import http from "./interceptors";
import Qs from 'qs'; //如果不需要请注释
export function getRequest (url, data = {}) {
return new Promise((resolve, reject) => {
http
.get(url, {
params: data
})
.then(response => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
export function postRequest (url, data = {}) {
return new Promise((resolve, reject) => {
http
.post(url, /*Qs.stringify((data)*/data))
.then(response => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
interceptors.js
import axios from "axios";
let againNum = 0;
//在main.js设置全局的请求次数,请求的间隙
const http = axios.create();
http.defaults.timeout = 15000;
http.defaults.withCredentials = true;
//请求拦截
http.interceptors.request.use(
config => {
//Content-Type 根据实际场景配置application/json 还是 application/x-www-form-urlencoded
//if (config.method === 'post') {
// config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
//}
return config;
},
err => {
return Promise.reject(err);
}
);
//响应拦截
http.interceptors.response.use(
response => {
return response.data;
},
err => {
let config = err.config;
//如果配置不存在或未设置重试选项,则返回错误信息
if (againNum < 1) {
if (err.message.includes("timeout")) {
againNum++;
const againHttp= new Promise(function (resolve) {
setTimeout(() => {
resolve();
}, 1000);
});
//请求重试
return againHttp.then(function () {
config.baseURL = "";
//超时不在发送
return http(config);
});
}
} else {
return Promise.reject(err.response);
}
}
);
export default http;
urlconfig.js
//统一管理地址
// export const baseUrl = "/api-proxy"; //本地开发 接口代理
export const baseUrl = "域名1";
export const baseUrl_New = "域名2";
index.js
//引入封装的方法和接口域名
import { postRequest, getRequest } from "./axios";
import { baseUrl, baseUrl_New } from "./urlconfig";
export const postDemo=(data)=>{
return postRequest(`${baseUrl}/xxxx`,data)
}
export const getDemo=(data)=>{
return getRequest(`${baseUrl_New }/xxxx`,data)
}
test.vue
<template>
<div>
....
</div>
</template>
<script>
import {postDemo} '@/httpClient/index.js'
export default{
data(){
return {}
},
methods:{},
mounted(){
postDemo({
参数
}).then(res=>{
}).catch(err=>{
})
}
}
</script>
更多推荐
已为社区贡献1条内容
所有评论(0)