SpringBoot解决ajax跨域问题的方法
SpringBoot解决ajax跨域,供大家参考,具体内容如下
一、第一种方式
1、编写一个支持跨域请求的Configuration
importorg.springframework.context.annotation.Configuration; importorg.springframework.web.servlet.config.annotation.CorsRegistry; importorg.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** *处理AJAX请求跨域的问题 *@authorLevin *@time2017-07-13 */ @Configuration publicclassCorsConfigextendsWebMvcConfigurerAdapter{ staticfinalStringORIGINS[]=newString[]{"GET","POST","PUT","DELETE"}; @Override publicvoidaddCorsMappings(CorsRegistryregistry){ registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS) .maxAge(3600); } }
2、HTTP请求接口
@RestController publicclassHelloController{ @Autowired HelloServicehelloService; @GetMapping(value="/test",produces=MediaType.APPLICATION_JSON_UTF8_VALUE) publicStringquery(){ return"hello"; } }
二、第二种方式(推荐)
PS:第一种存在一个问题,当服务器抛出500的时候依旧存在跨域问题
@SpringBootApplication @ComponentScan @EnableDiscoveryClient publicclassManagementApplication{ publicstaticvoidmain(String[]args){ SpringApplication.run(ManagementApplication.class,args); } privateCorsConfigurationbuildConfig(){ CorsConfigurationcorsConfiguration=newCorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.addExposedHeader(HttpHeaderConStant.X_TOTAL_COUNT); returncorsConfiguration; } /** *跨域过滤器 * *@return */ @Bean publicCorsFiltercorsFilter(){ UrlBasedCorsConfigurationSourcesource=newUrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**",buildConfig());//4 returnnewCorsFilter(source); } }
2、index.html
跨域请求
三、第三种方式,编写Filter过滤器
packagecom.cci.market.common.filter; importjava.io.IOException; importjavax.servlet.Filter; importjavax.servlet.FilterChain; importjavax.servlet.FilterConfig; importjavax.servlet.ServletException; importjavax.servlet.ServletRequest; importjavax.servlet.ServletResponse; importjavax.servlet.http.HttpServletResponse; importorg.springframework.stereotype.Component; /** *处理跨域问题 *@authorMR.ZHENG *@date2016/08/08 * */ @Component publicclassOriginFilterimplementsFilter{ @Override publicvoidinit(FilterConfigfilterConfig)throwsServletException{ } @Override publicvoiddoFilter(ServletRequestreq,ServletResponseres, FilterChainchain)throwsIOException,ServletException{ HttpServletResponseresponse=(HttpServletResponse)res; response.setHeader("Access-Control-Allow-Origin","*"); response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,DELETE,PUT"); response.setHeader("Access-Control-Max-Age","3600"); response.setHeader("Access-Control-Allow-Headers","x-requested-with"); chain.doFilter(req,res); } @Override publicvoiddestroy(){ //TODOAuto-generatedmethodstub } }
四、Nginx跨域配置
Nginx跨域也比较简单,只需添加以下配置即可。
location/{ proxy_passhttp://localhost:8080; if($request_method='OPTIONS'){ add_header'Access-Control-Allow-Origin''*'; add_header'Access-Control-Allow-Methods''GET,POST,OPTIONS'; add_header'Access-Control-Allow-Headers''DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token'; add_header'Access-Control-Max-Age'1728000; add_header'Content-Type''text/plain;charset=utf-8'; add_header'Content-Length'0; return204; } if($request_method='POST'){ add_header'Access-Control-Allow-Origin''*'; add_header'Access-Control-Allow-Methods''GET,POST,OPTIONS'; add_header'Access-Control-Allow-Headers''DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token'; add_header'Access-Control-Expose-Headers''DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token'; } if($request_method='GET'){ add_header'Access-Control-Allow-Origin''*'; add_header'Access-Control-Allow-Methods''GET,POST,OPTIONS'; add_header'Access-Control-Allow-Headers''DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token'; add_header'Access-Control-Expose-Headers''DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token'; } }
其中:add_header'Access-Control-Expose-Headers'务必加上你请求时所带的header。例如本例中的“Token”,其实是前端传给后端过来的。如果记不得也没有关系,浏览器的调试器会有详细说明。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。