vue使用axios调用接口地址,配置一个服务端的代理,隐藏真实请求地址
- vue.config.js配置
module.exports = {
...
devServer: {
open: true,
port: port,
overlay: {
// 在浏览器不显示编译的警告
warnings: false,
// 在浏览器上显示编译的错误
errors: true
},
proxy: {
['/api']: {
// 使用环境变量中的值
target: baseURL, //服务端接口地址
changeOrigin: true,
pathRewrite: {
'^/api': 'api',
},
},
},
}
}
- request.js配置
/**
@description axios初始化
*/
const instance = axios.create({
baseURL: '/',
timeout: requestTimeout,
headers: {
'Content-Type': contentType,
},
})
- api.js配置
import request from './request'
export async function login(data) {
return request({
url: '/api/user/login',
method: 'post',
data,
})
}
请求地址:http://localhost:*//api/user/login
真实请求地址:baseURL//api/user/login
- 打包情况下启动项目,需要配置nginx
server {
listen 自己设定的端口;
# listen 8001;
server_name localhost;
# 主要
location ~^/api/(.*)$ {
proxy_pass baseURL/api/$1?$args;
}
location /{
root 文件路径;
# root G:/;
}
}