Vue项目部署服务器时,遇到的问题,我也是整理了非常久才得知(Linux服务器架设知识不牢靠)
我们在生产环境时因为浏览器的机制需要配置代理服务器才能进行正确的访问我们的后端接口,
假设我们后端接口是127.0.0:8004,我们配置代理如下
前端生产环境的代理设置
devServer: {
proxy: {
'/api': {
target: 'http://127.0.0.1:8004',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
post请求
我们请求的后端接口是127.0.0.1:8004/rootlogin
try {
const response = axios.post('api/rootlogin', {
userid: this.userid,
password: this.password,
// 其他参数...
});
console.log(response.data);
} catch (error) {
console.error(error);
}
然后将dist部署上线的时候这个代理并不会跟着打包到服务器
假设我们将项目打包到的地址是127.0.0.2:89地址
那么这时候数据请求将请求的是127.0.0.2:89/api/rootlogin地址,但是我们需要请求的接口是127.0.0.1:8004地址
这时候就需要用到nginx的反向代理了
首先进入配置文件
server
{
listen 80;
listen 83;
server_name 127.0.0.2:89;
index index.php index.html index.htm default.php default.htm default.html;
root /www/wwwroot/Web/dist;.#......................................在这里配置我们的反向代理
location /api/ {
# 只有路径中包含 /api 时才会进行代理
proxy_pass http://127.0.0.1:8004/; # 这是你的后端地址#注意当后面有/时才会将api去掉,否则将url拼接
# 其他代理相关配置
}.#......................................在这里配置我们的反向代理
配置好了代理之后就可以重启服务器了