问题描述
项目中需要请求搜狐的接口http://pv.sohu.com/cityjson获取客户端当前ip,但这个接口不允许ajax跨域请求,解决方案如下(跨域通用)
开发环境
//在uni-app 的项目中 manifest.json文件中配置跨域代理
"h5": {
"devServer": {
"port": 8000,
"disableHostCheck": true,
"proxy": {
"/sohu": {
"target": "http://pv.sohu.com",
"changeOrigin": true,
"secure": false,
"pathRewrite": {
"^/sohu": ""
}
}
}
}
}
//在组件中访问
uni.request({
url: '/sohu/cityjson',
success: (res) => {
console.log(res.data);
}
});
生产环境
配置 nginx
server {
listen 80;
server_name 自己项目的访问域名;
root /var/www/html/test;
index index.html;
#这一行是解决跨域重点,并且要放在下面两个location之前
location /sohu {
rewrite ^/sohu/(.*)$ /$1 break;
proxy_pass http://pv.sohu.com;
}
location / {
try_files $uri $uri/ @router;
index index.html;
}
location @router {
rewrite ^.*$ /index.html last;
}
}