在我的项目开发中,咱们很常见的一个问题是,本地是localhost
开发的,接口个别是给IP
地址,例如http://192.168.13.14/api
, 这样间接在我的项目中调用接口 浏览器会报跨域谬误, 因为localhost
和http://192.168.13.14
并不是同源的。
个别咱们的解决办法是在webpack
中设置代理,配置devServer
:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://192.168.13.14/api',
changeOrigin : true
}
}
}
}
设置当前,在接口拜访 假如为http://localhost:8080/api
时,会转发到http://192.168.13.14/api
去.
所以,如果不是通过devServer
的形式,该怎么做呢?
接手的我的项目就没有配置webpack devServer
,认真看是设置了Access-Control-Allow-Origin: http://localhost:8054
来解决接口跨域的,然而,这个我的项目的鉴权形式是cookie
, 这里地址http://localhost:8054
和接口地址==不同源导致cookie
设置失败==
那么当初的想法要让浏览器地址与接口地址同源,那么cookie天然可能设置胜利了!
能够通过配置nginx
来实现。
配置:
server {
listen 8055 {
// 步骤1
location / {
proxy_pass: http://localhost:8054/;
}
// 步骤2
location /api {
proxy_pass: http://192.169.13.14;
}
}
}
我拜访的地址原本是http://localhost:8054
, 这里我监听8055端口。
- 步骤1 做地址的代理,当拜访
http://localhost:8055
时,会映射到http://localhost:8054
- 步骤2 做接口的代理,当拜访
http://localhost:8055/api/xxxx
时,会映射到http://192.169.13.14/api/xxxx
-
还有一步,在我的项目中,要动静配置接口地址:
const apiAddress = window.location.protocol + '//' + window.location.host + '/api';
这样,浏览器地址与接口地址就都是localhost:8055
结尾的,不存在跨域的问题,cookie
就能胜利设置
发表回复