1、web前端开发经常会遇到跨域访问,如果没有办法让后台开放访问域,调用接口就会被浏览器拦截。解决跨域问题的方案,可以搭建一个后台服务做中间转发,也可以用nginx转发。
2、nginx部署配置,打开conf/nginx.conf文件
server {
listen 8080;
server_name localhost;
root html;
location / {
#index index.html index.htm;
#解决vue去掉#号问题,将vue打包的dist文件下文件放到html目录
try_files $uri $uri/ /index.html;
}
#请求http://localhost:8080/api,将该请求转发到百度api,则保证请求在同一个域,解决跨域问题
location /api {
proxy_pass http://api.baidu.com/api;
}
}
3、nginx开发vue项目配置
server {
listen 8080;
server_name localhost;
root html;
location / {
#vue运行dev在8088端口
proxy_pass http://localhost:8088;
}
#请求http://localhost:8080/api,将该请求转发到百度api,则保证请求在同一个域,解决跨域问题
location /api {
proxy_pass http://api.baidu.com/api;
}
}
vue项目dev运行在8088端口,访问nginx8080端口,转发到vue的dev环境,从而达到请求域和访问域一致
4、上线部署,需要将localhost替换成服务器对应域名