Springboot 实现跨域访问无需使用jsonp的实现代码

Springboot 实现跨域访问 无需使用jsonp

在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/**");
  }
}

总结

以上所述是小编给大家介绍的Springboot 实现跨域访问无需使用jsonp的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

你可能感兴趣的:(Springboot 实现跨域访问无需使用jsonp的实现代码)