后端跨域配置信息:
1 全局配置:
package com.es.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author kuai
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
2 自定义Filter类 解析跨域
@WebFilter
@Configuration
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
// response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
chain.doFilter(req, res);
}
}
3 使用注解
@CrossOrigin注解
在Controller类或者处理用户请求的方法上加@CrossOrigin注解。
@CrossOrigin(origins = "http://localhost:63342", maxAge = 3600)
@RestController
public class DemoController {
@RequestMapping("/fun")
public String fun(String p){
System.out.println("param "+p);
return "test"+id}";
}
}
前台html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.ajax({
type:"GET",
url:"http://localhost:8080/search/java/1/10",
dataType:"json",
success:function(data){
console.log(data.valueOf());
}
});
});
</script>
</head>
<body style="text-align: center">
<div id="swarp" >
</div>
</body>
</html>