跨域处理
跨域定义
指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制
解决方案
注意:
跨域请求除GET(简单请求)外的其它请求(如POST/PUT/DELETE)等会产生一次预检请求,预检请求会将原请求转换为OPTIONS请求。 如果服务端设置了防火墙,防火墙需要放开(GET/POST/PUT/DELETE/OPTIONS)请求。
- JSONP(不推荐)
只支持get请求、不支持post请求
- nginx反向代理
if ( $request_method = 'OPTIONS' ) {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Max-Age' '604800';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Access-Token,Blog-ID';
return 200;
}
server {
listen 80;
server_name localhost;
location / {
add_header 'Access-Control-Allow-Origin' *;
add_header 'Access-Control-Allow-Credentials' 'true';
#允许请求的方法,比如 GET/POST/PUT/DELETE
add_header 'Access-Control-Allow-Methods' *;
add_header 'Access-Control-Allow-Headers' *;
root /usr/share/nginx/html;# 根⽬录
index index.html index.htm; # 默认⾸⻚
}
}
- 服务端增加
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 所有接口
.allowCredentials(true) // 是否发送 Cookie
.allowedOriginPatterns("*") // 支持域
.allowedMethods("GET", "POST", "PUT", "DELETE") // 支持方法
.allowedHeaders("*")
.exposedHeaders("*");
}
}