问题现象
当我们当前的域名与请求接口的域名不在同一个域名下时,在浏览器Console下会看到,跨域的错误提示
- 当前域名http://log.demo.finrunchain.com:8000
- 请求接口域名:http://hbcc.demo.finrunchain.com:8000
当在前端页面通过angularjs请求接口域名的数据时,会报跨域错误
解决跨域方法
nginx配置跨域
- 方法一
1
2
3
4
5add_header Access-Control-Allow-Origin * always;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS always;
add_header Access-Control-Allow-Credentials true always;
add_header Access-Control-Allow-Headers DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,x-auth-token always;
add_header Access-Control-Max-Age 1728000 always; - 方法二以上两种方法都无效
1
2
3
4
5
6
7
8
9
10
11add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET,POST,PUT,DELETE,OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
# if ($request_method = 'OPTIONS') {
# add_header 'Access-Control-Max-Age' 1728000;
# add_header 'Content-Type' 'text/plain; charset=utf-8';
# add_header 'Content-Length' 0;
# return 204;
# } - 方法三
在本域名下增加接口,例如:http://log.demo.finrunchain.com:8000/hbcc
修改nginx配置文件:
location /hbcc {
rewrite ^/getCat/(.*)$ /$1 break;
proxy_pass http://localhost:4040/;
}
重启nginx,跨域问题解决
v1.5.2