假定本地项目运行起来的地址为:localhost:8080
假定服务器api接口地址为:xxx.com/api
如下思路
1.本地通过nginx搭建localhost:8081
的服务,将vue项目和api接口代理起来,保持同域解决跨域问题
2.代码中修改api请求地址为localhost:8081/api
3.nginx配置监听8081端口以开启localhost:8081
服务,将所有来自/api
的请求代理到xxx.com/api
,其他请求代理到localhost:8080
4.浏览器访问localhost:8081
本地nginx如下配置
server {
listen 8081;
server_name localhost;
location ^~ /api/ {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,X-Token,token';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Requested-With,X-Token';
add_header 'Access-Control-Allow-Methods' 'GET,POST,PUT,OPTIONS';
#rewrite ^/api/(.*) /$1 break; 如果需要将正式环境中的api地址不包含/api/需要重写
proxy_pass https://xxx.com;
}
location / {
proxy_pass http://localhost:8080;
}
#location /{
# root /home/website/shijun;
# try_files $uri $uri/ /index.html;
#}
}
网友评论