1.配置跨域有两种方式
1.在每个controller中设置2.新建一个配置类WebMvcConfig配置全局的跨域 2.前端访问
1.配置跨域有两种方式
1.在每个controller中设置
@ResponseBody
@RequestMapping(value
= "/cs", method
= RequestMethod
.POST
)
public String
cs(HttpServletResponse response
, HttpServletRequest request
) {
response
.setHeader("Access-Control-Allow-Origin", request
.getHeader("Origin"));
response
.setHeader("Access-Control-Allow-Credentials", "true");
return "跨域测试";
}
这种方式只能确保这一个controller中可以跨域
2.新建一个配置类WebMvcConfig配置全局的跨域
import org
.springframework
.boot
.autoconfigure
.web
.servlet
.WebMvcAutoConfiguration
;
import org
.springframework
.context
.annotation
.Configuration
;
import org
.springframework
.web
.servlet
.config
.annotation
.CorsRegistry
;
import org
.springframework
.web
.servlet
.config
.annotation
.WebMvcConfigurerAdapter
;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry
) {
registry
.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS","TRACE")
.allowCredentials(true);
}
}
registry.allowedOrigins(““)设置跨域访问的域名,如果是,默认都可以访问。registry.allowCredentials(true)设置是否允许客户端发送cookie信息。默认是false,但是如果不接受cookie,则会导致客户端获取的session不同这种问题
2.前端访问
如果前端发送ajax请求保证同一个会话中session相同,则需设置 withCredentials: true
$
.ajax({
url
: "http://localhost:9001/loginOut",
dataType
: "json",
type
: "get",
xhrFields
: {
withCredentials
: true
},
crossDomain
: true,
success
: function(data
) {
console
.log(data
)
},
error
: function() {
alert("token认证失败")
}
});
})