Angular开发服务器跨域请求外部域名时的Cookie处理方案
不用搞复杂的网关或反向代理,Angular自带的开发服务器代理就能完美解决这个问题——核心是让浏览器只和本地Angular服务通信,由Angular服务帮你转发请求到目标服务器,直接绕开浏览器的跨域限制,具体步骤:
- 在Angular项目根目录新建
proxy.conf.json文件,复制以下内容:
{ "/api": { "target": "http://example.com:8080", "secure": false, "changeOrigin": true, "withCredentials": true, "pathRewrite": { "^/api": "" } } }
/api是请求代理前缀:比如原来请求http://example.com:8080/login,现在改成请求/api/login即可target填目标服务器地址http://example.com:8080changeOrigin设为true,确保请求头的Host能匹配目标服务器要求withCredentials必须开启,保证JSESSIONID这类Cookie能被正确转发和保存
- 修改
package.json里的启动命令,加上代理配置:
"scripts": { "start": "ng serve --proxy-config proxy.conf.json", // 其他命令保持不变 }
- 调整Angular中的请求代码,把原来的绝对地址换成相对路径,比如原来的:
this.http.post('http://example.com:8080/login', loginBody, { withCredentials: true })
改成:
this.http.post('/api/login', loginBody, { withCredentials: true })
- 重启Angular开发服务器,现在所有以
/api开头的请求都会被自动转发到example.com:8080,浏览器会认为是同域请求,JSESSIONIDCookie就能正常携带和使用了。
补充说明:之前改hosts没用是因为浏览器的跨域判断依据是**页面域名(localhost:4200)和请求域名(example.com)**是否一致,哪怕你把example.com映射到本地,页面和请求的域名还是不匹配,依然会触发跨域限制;而代理是让请求走Angular服务器转发,浏览器只和localhost:4200通信,自然就不存在跨域问题了。
内容的提问来源于stack exchange,提问作者Alfonso Tienda
相关产品推荐
相关产品推荐

