在springboot的拦截器中添加respone的头信息即可
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //String origin = (String) request.getRemoteHost()+":"+request.getRemotePort(); response.addHeader("Access-Control-Allow-Origin", "*"); //System.out.println("Access-Control-Allow-Origin"); response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); //System.out.println("Access-Control-Allow-Methods"); response.addHeader("Access-Control-Max-Age", "3600"); //System.out.println("Access-Control-Max-Age"); response.addHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization"); //System.out.println("Access-Control-Allow-Headers"); response.addHeader("Access-Control-Allow-Credentials","true"); //System.out.println("Access-Control-Allow-Credentials"); String api_key = request.getParameter("api_key"); String api_secret = request.getParameter("api_secret"); ; if (check(api_key,api_secret)){ return true; } response.sendError(400,"api_key or api_secret are error"); return false; }
@Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer { @Bean APIIntercepter apiIntercepter() { return new APIIntercepter(); } @Override public void addInterceptors(InterceptorRegistry registry) { // 添加一个拦截器,连接以/v1为前缀的 url路径 registry.addInterceptor(loginIntercepter()).addPathPatterns("/admin/**"); registry.addInterceptor(apiIntercepter()).addPathPatterns("/v1/**"); } }