前端跨域处理
如果后台使用了CORS则不需要往后看了。如果前端解决跨域,那么默认情况下,前端接口请求的是http://localhost:8080
开发环境 利用vue.config.js中的devServer配置,在这里配置proxy 在根目录中创建vue.config.js文件
module.exports = { devServer: { proxy: "http://localhost:3000" } }
如果在一个项目中使用了多个后台,那么需要以下配置,配置前需要和后台进行沟通,把不同的接口前缀设置成不一样的
module.exports = { devServer: { proxy: { '/前缀1': { target: '要跨域的url' }, '/前缀2': { target: '要跨域的url' } } } }
生产环境
找到服务器中的nginx安装位置(问后台,需要有服务器的用户名和密码),找到配置文件nginx.conf 我们只需要配置server即可
`server { listen 80; server_name localhost; }
配置我们对应的vue项目的根目录
location / { root html; index index.html index.htm; }
如果使用history模式,则按照下面的配置进行配置
location / { root html; try_files uri/ /index.html; }
前端可以和后台沟通,添加同意的前缀 /api 或者其他的统一前缀
location /api { proxy_pass http://localhost:3000; }
如果需要多个后台地址的跨域
location /其他前缀 { proxy_pass 要代理的地址; } } ` build之后,把dist目录中的文件,放在nginx服务器所配置的服务器根目录中(默认是html),然后打开服务,访问http://localhost,可以访问到内容,但是接口不通,按照上面的方式进行配置,可以实现对应的跨域操作