查看: 1439|回复: 0

[Java语言] SpringBoot解决ajax跨域问题的方法

发表于 2018-4-16 08:00:05

SpringBoot解决ajax跨域,供大家参考,具体内容如下

一、第一种方式

1、编写一个支持跨域请求的 Configuration

  1. import org.springframework.context.annotation.Configuration;
  2. import org.springframework.web.servlet.config.annotation.CorsRegistry;
  3. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  4. /**
  5. * 处理AJAX请求跨域的问题
  6. * @author Levin
  7. * @time 2017-07-13
  8. */
  9. @Configuration
  10. public class CorsConfig extends WebMvcConfigurerAdapter {
  11. static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" };
  12. @Override
  13. public void addCorsMappings(CorsRegistry registry) {
  14. registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS)
  15. .maxAge(3600);
  16. }
  17. }
复制代码

2、HTTP请求接口

  1. @RestController
  2. public class HelloController {
  3. @Autowired
  4. HelloService helloService;
  5. @GetMapping(value = "/test", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
  6. public String query() {
  7. return "hello";
  8. }
  9. }
复制代码

二、 第二种方式(推荐)

PS:第一种存在一个问题,当服务器抛出 500 的时候依旧存在跨域问题

  1. @SpringBootApplication
  2. @ComponentScan
  3. @EnableDiscoveryClient
  4. public class ManagementApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(ManagementApplication.class, args);
  7. }
  8. private CorsConfiguration buildConfig() {
  9. CorsConfiguration corsConfiguration = new CorsConfiguration();
  10. corsConfiguration.addAllowedOrigin("*");
  11. corsConfiguration.addAllowedHeader("*");
  12. corsConfiguration.addAllowedMethod("*");
  13. corsConfiguration.addExposedHeader(HttpHeaderConStant.X_TOTAL_COUNT);
  14. return corsConfiguration;
  15. }
  16. /**
  17. * 跨域过滤器
  18. *
  19. * @return
  20. */
  21. @Bean
  22. public CorsFilter corsFilter() {
  23. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  24. source.registerCorsConfiguration("/**", buildConfig()); // 4
  25. return new CorsFilter(source);
  26. }
  27. }
复制代码

2、index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>跨域请求</title>
  6. <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
  7. </script>
  8. <script>
  9. $(document).ready(function(){
  10. $("button").click(function(){
  11. $.ajax({url:"http://localhost:8080/test",success:function(result){
  12. $("#p1").html(result);
  13. }});
  14. });
  15. });
  16. </script>
  17. </head>
  18. <body>
  19. <p width="500px" height="100px" id="p1"></p>
  20. <button>获取其他内容</button>
  21. </body>
  22. </html>
复制代码

三、第三种方式,编写Filter过滤器

  1. package com.cci.market.common.filter;
  2. import java.io.IOException;
  3. import javax.servlet.Filter;
  4. import javax.servlet.FilterChain;
  5. import javax.servlet.FilterConfig;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.ServletRequest;
  8. import javax.servlet.ServletResponse;
  9. import javax.servlet.http.HttpServletResponse;
  10. import org.springframework.stereotype.Component;
  11. /**
  12. * 处理跨域问题
  13. * @author MR.ZHENG
  14. * @date 2016/08/08
  15. *
  16. */
  17. @Component
  18. public class OriginFilter implements Filter {
  19. @Override
  20. public void init(FilterConfig filterConfig) throws ServletException {
  21. }
  22. @Override
  23. public void doFilter(ServletRequest req, ServletResponse res,
  24. FilterChain chain) throws IOException, ServletException {
  25. HttpServletResponse response = (HttpServletResponse) res;
  26. response.setHeader("Access-Control-Allow-Origin", "*");
  27. response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
  28. response.setHeader("Access-Control-Max-Age", "3600");
  29. response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
  30. chain.doFilter(req, res);
  31. }
  32. @Override
  33. public void destroy() {
  34. // TODO Auto-generated method stub
  35. }
  36. }
复制代码

四、Nginx跨域配置

Nginx跨域也比较简单,只需添加以下配置即可。

  1. location / {
  2. proxy_pass http://localhost:8080;
  3. if ($request_method = 'OPTIONS') {
  4. add_header 'Access-Control-Allow-Origin' '*';
  5. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  6. 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';
  7. add_header 'Access-Control-Max-Age' 1728000;
  8. add_header 'Content-Type' 'text/plain; charset=utf-8';
  9. add_header 'Content-Length' 0;
  10. return 204;
  11. }
  12. if ($request_method = 'POST') {
  13. add_header 'Access-Control-Allow-Origin' '*';
  14. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  15. 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';
  16. 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';
  17. }
  18. if ($request_method = 'GET') {
  19. add_header 'Access-Control-Allow-Origin' '*';
  20. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  21. 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';
  22. 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';
  23. }
  24. }
复制代码

其中:add_header 'Access-Control-Expose-Headers' 务必加上你请求时所带的header。例如本例中的“Token”,其实是前端传给后端过来的。如果记不得也没有关系,浏览器的调试器会有详细说明。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。



回复

使用道具 举报