接着上篇——简单的springboot-vue先后端分离登陆Session拦截的demo,其中跨域是经过springboot后端全局设置的,可是碰到了奇怪的问题,用了个不优雅的方式解决。
因而想到使用Nginx跨域应该就不会如此了。php
http://nginx.org/ 下载稳定版,解压缩。
查看配置文件 /nginx-1.16.0/conf/nginx.conf
:html
#gzip on; server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; } #error_page 404 /404.html;
默认监听端口是80,/
是相对路径下的html
目录。前端
netstat -ano|findstr 3306
tasklist|findstr 3448
taskkill /pid #{pid} /F
tasklist|findstr mysql
肯定端口没被占用后,默认的80端口先跑起来。vue
start nginx
,一闪而过正常,==不要使用双击exe方式==tasklist|findstr nginx
localhost:80
显示 Nginx 欢迎页,OK修改默认80端口为自定义端口8081mysql
nginx.exe -s reload
nginx经常使用命令(==windows-dos环境加.exe后缀,好比 nginx.exe -t==)
(cd 到安装跟目录执行命令,好比 xxx/nginx-1.16.0/)ios
start nginx 启动 nginx -v 查看Nginx的版本号 nginx -t 检查配置文件的有效性 nginx -s 当即关闭 nginx -s quit 处理完当前的请求后关闭 nginx -s reload 修改完配置文件后重载 nginx -s reopen 打开日志文件
打包部署vue-cli项目nginx
location / { root html/dist; index index.html index.htm; }
nginx.exe -t
,重载配置nginx.exe -s reload
axios.defaults.baseURL
,baseURL的做用也交给Nginx的proxy_pass。#user nobody; # 启动多worker进程 #worker_processes 1; worker_processes auto; #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压缩 gzip on; #gzip on; server { # nginx服务器对外8081端口 listen 8081; server_name localhost; #charset koi8-r; # 日志输出 access_log logs/myvue.access.log main; #access_log logs/host.access.log main; # 静态文件配置 location / { root html/dist; index index.html index.htm; } #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; } # 反向代理springboot接口服务 location /api/ { # 前端请求: /api/login 代理后: http://127.0.0.1:8080/login proxy_pass http://127.0.0.1:8080/; # 解决springboot中获取远程ip的问题 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_http_version 1.1; proxy_set_header Connection ""; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #}
proxyTable
,开发环境本地调试用)proxy_pass
,开发到上线)addCorsMappings
一劳永逸,前端无关性)springboot
)配置跨域是很方便的Windows-dos下使用 nginx -s stop; nginx -s reload
等喜闻乐见命令时,报找不到命令。spring
上面通用的是Linux环境的,windows-dos下使用这种
nginx.exe -s stop
。sql