在项目开发中,咱们很常见的一个问题是,本地是localhost
开发的,接口通常是给IP
地址,例如http://192.168.13.14/api
, 这样直接在项目中调用接口 浏览器会报跨域错误, 由于localhost
和http://192.168.13.14
并非同源的。webpack
通常咱们的解决方法是在webpack
中设置代理,配置devServer
:nginx
module.exports = { devServer: { proxy: { '/api': { target: 'http://192.168.13.14/api', changeOrigin : true } } } }
设置之后,在接口访问 假设为http://localhost:8080/api
时,会转发到http://192.168.13.14/api
去.web
因此,若是不是经过devServer
的方式,该怎么作呢?api
接手的项目就没有配置webpack devServer
,仔细看是设置了Access-Control-Allow-Origin: http://localhost:8054
来解决接口跨域的,可是,这个项目的鉴权方式是cookie
, 这里地址http://localhost:8054
和接口地址==不一样源致使cookie
设置失败==跨域
那么如今的想法要让浏览器地址与接口地址同源,那么cookie天然可以设置成功了!浏览器
能够经过配置nginx
来实现。cookie
配置:spa
server { listen 8055 { // 步骤1 location / { proxy_pass: http://localhost:8054/; } // 步骤2 location /api { proxy_pass: http://192.169.13.14; } } }
我访问的地址原本是http://localhost:8054
, 这里我监听8055端口。代理
http://localhost:8055
时,会映射到http://localhost:8054
http://localhost:8055/api/xxxx
时,会映射到http://192.169.13.14/api/xxxx
还有一步,在项目中,要动态配置接口地址:code
const apiAddress = window.location.protocol + '//' + window.location.host + '/api';
这样,浏览器地址与接口地址就都是localhost:8055
开头的,不存在跨域的问题,cookie
就能成功设置