前言
最近部署前端vue项目到服务器上,因为vue的接口做了后端接口代理,用Nginx部署的时候出现登录接口报404和500的错误
vue代理部分代码
proxyTable: {
'/chain-api': {
target: 'http://xx.xxx.xx.xx:9090',
changeOrigin:true,
pathRewrite: {
'^/chain-api': '/'
}
}
},
问题一:部署完成页面报错500
解决
因nginx部署创建的路径为chain-trace-web/dist,将vue打包npm run build之后的dist文件存放在该位置,但是写的时候多加了斜杠,如下所示
root /chain-trace-web/dist;
导致找不到页面所以报500错误,只要更改为如下配置即可
location / {
root chain-trace-web/dist;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
问题二:登录后点击登录按钮调用后端接口,控制台报错接口404,页面也无后续反应
解决
因在vue做了接口代理,所以用nginx处理反向代理的时候得在nginx.conf文件中增加代理配置,但缺少斜杠,原本写法为
location /chain-api {
proxy_pass http://10.241.43.20:9090/;
}
更改为
location /chain-api/ {
proxy_pass http://10.241.43.20:9090/;
}
即可成功转发访问后端接口路径了
最后附上完整的nginx配置文件
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 8080; #前端监听端口
server_name localhost; #这里填写对应的域名或ip地址
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root chain-trace-web/dist;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /chain-api/ {
proxy_pass http://xx.xxx.xx.xx:9090/;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
# server {
# listen 80;
# server_name chain-trace-web;
# location / {
# root chain-trace-web/dist;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
附linux安装nginx参考文章
linux服务器安装nginx及使用
Linux服务器安装Nginx详细步骤(多次安装,过程详细)
CentOS7源码方式安装nginx-1.18.0