浏览器请求不同域名的接口必须在接口后端设置允许跨域
假设:
请求域名: dfg.com
请求接口: abc.com/api/get
浏览器会对“请求接口”发送 OPTIONS 和 GET 请求,2个请求响应都正常,则实现跨域
- OPTIONS请求获得允许跨域的Origin,Headers,Methods
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:*
Access-Control-Allow-Methods:POST,GET,OPTIONS
Access-Control-Allow-Origin:https://dfg.com
- GET请求处理业务逻辑
注意:如果请求接口允许所有Method请求,那么接口就会被处理2次
在Spring Boot项目中,可以直接使用@CrossOrigin 注解进行跨域,而无需在controller中写 OPTIONS 和 GET|POST 方法
@CrossOrigin(origins = "*")
如果使用Nginx反向代理,可以针对 OPTIONS 请求响应允许跨域Headers,而无需处理业务逻辑
location ^~/api {
add_header Access-Control-Allow-Origin https://abc.com always;
add_header Access-Control-Allow-Headers "Accept,Accept-Encoding,Accept-Language,Connection,Content-Length,Content-Type,Host,Origin,Referer,User-Agent,Authorization,x-requested-with,content-type";
add_header Access-Control-Allow-Methods "GET, POST, PUT, OPTIONS";
add_header Access-Control-Allow-Credentials true;
if ($request_method = 'OPTIONS') {
return 200;
}
proxy_connect_timeout 600s;
proxy_read_timeout 600s;
proxy_send_timeout 600s;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
proxy_redirect default;
client_max_body_size 20m;
}