CORS跨域原理详解
Spring解决跨域
- 响应头设置跨域
@RequestMapping(value = "/ajax")
public @ResponseBody
Customer ajax(Integer id, HttpServletResponse response) {
Customer customer = customerService.queryCustomerById(id);
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
response.setHeader("Access-Control-Allow-Credentials", "true");
return customer;
}
- Spring注解跨域
@CrossOrigin 可添加到方法上,也可添加到类上
// orgins=''http://localhost:63343"表示允许域名为
http://localhost:63343 访问该方法
// origins="*", 表示允许所有其他的网站访问该方法
@CrossOrigin(origins = "http://localhost:63343")
@RequestMapping(value = "/ajax")
public @ResponseBody
Customer ajax(Integer id, HttpServletResponse response) {
Customer customer = customerService.queryCustomerById(id);
return customer;
}
网友评论