From: https://www.jianshu.com/p/e57ed1ee3070

利用注解的方式解决AJAX请求跨域问题

一、第一种方式:

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

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;/*** 处理AJAX请求跨域的问题* @author Levin* @time 2017-07-13*/
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" };@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS).maxAge(3600);}
}

2、HTTP请求接口

@RestController
public class HelloController {@AutowiredHelloService helloService;@GetMapping(value = "/test", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)public String query() {return "hello";}
}

二、 第二种方式(推荐)

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

@SpringBootApplication
@ComponentScan
@EnableDiscoveryClient
public class ManagementApplication {public static void main(String[] args) {SpringApplication.run(ManagementApplication.class, args);}private CorsConfiguration buildConfig() {CorsConfiguration corsConfiguration = new CorsConfiguration();corsConfiguration.addAllowedOrigin("*");corsConfiguration.addAllowedHeader("*");corsConfiguration.addAllowedMethod("*");corsConfiguration.addExposedHeader(HttpHeaderConStant.X_TOTAL_COUNT);return corsConfiguration;}/*** 跨域过滤器** @return*/@Beanpublic CorsFilter corsFilter() {UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", buildConfig()); // 4return new CorsFilter(source);}
}

2、index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>跨域请求</title>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){$("button").click(function(){$.ajax({url:"http://localhost:8080/test",success:function(result){$("#p1").html(result);}});});
});
</script>
</head>
<body><p width="500px" height="100px" id="p1"></p>
<button>获取其他内容</button>
</body>
</html>

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

package com.cci.market.common.filter;import java.io.IOException;import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Component;/*** 处理跨域问题* @author MR.ZHENG* @date 2016/08/08**/
@Component
public class OriginFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic 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-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);}@Overridepublic void destroy() {// TODO Auto-generated method stub}}

四、Nginx跨域配置

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

location / {proxy_pass http://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;return 204;}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”,其实是前端传给后端过来的。如果记不得也没有关系,浏览器的调试器会有详细说明。

SpringBoot解决ajax跨域问题相关推荐

  1. Spring Boot学习总结(6)——SpringBoot解决ajax跨域请求问题的配置

    ajax是一种创建交互式网页应用的网页开发技术,是一种用于创建快速动态网页的技术,通过在后台与服务器进行少量数据交换.而ajax的跨域问题则是请求了其他项目的接口地址,当协议.子域名.主域名.端口号中 ...

  2. php json -gt;访问,【转】Php+ajax+jsonp解决ajax跨域问题

    首先:jsonp是json用来跨域的一个东西. 原理是通过script标签的跨域特性来绕过同源策略. 发送端: $.ajax({ type : "post", url : &quo ...

  3. 记一次SpringBoot解决CROS跨域问题(CROS)

    记一次SpringBoot解决CROS跨域问题(CROS) 使用注解@CrossOrigin(局部跨域 后端创建注入切面 @Target({ElementType.TYPE, ElementType. ...

  4. 用iframe设置代理解决ajax跨域请求问题

    用iframe设置代理解决ajax跨域请求问题 参考文章: (1)用iframe设置代理解决ajax跨域请求问题 (2)https://www.cnblogs.com/ranzige/p/370965 ...

  5. 解决AJAX跨域WCF的问题详解

    解决AJAX跨域WCF的问题详解 参考文章: (1)解决AJAX跨域WCF的问题详解 (2)https://www.cnblogs.com/jooucks/p/7159147.html 备忘一下.

  6. 使用SpringMVC解决Ajax跨域问题

    使用SpringMVC解决Ajax跨域问题 参考文章: (1)使用SpringMVC解决Ajax跨域问题 (2)https://www.cnblogs.com/mengyao/p/6294787.ht ...

  7. jsonp解决ajax跨域问题,用JSONP解决ajax跨域问题

    JSONP:JSON With Padding 要点: 1.script标签 2.用script标签加载资源是没有跨域问题的 概要: 在资源加载进来之前先定义一个函数,这个函数接受一个参数(数据),函 ...

  8. 如何解决ajax跨域问题(转)

    由 于此前很少写前端的代码(哈哈,不合格的程序员啊),最近项目中用到json作为系统间交互的手段,自然就伴随着众多ajax请求,随之而来的就是要解决 ajax的跨域问题.本篇将讲述一个小白从遇到跨域不 ...

  9. 如何解决ajax跨域问题

    原文:http://www.congmo.net/blog/2012/06/27/ajax-cross-domain/ 跨域问题 起 因是这样的,为了复用,减少重复开发,单独开发了一个用户权限管理系统 ...

最新文章

  1. 高效模式编写者的7个习惯
  2. Asynctask源码分析
  3. 用新语法写更简洁的ABAP代码
  4. aspx转发php_asp,php,aspx一句话合集
  5. win7连接sftp_SFTP远程连接服务器上传下载文件-vs2010项目实例
  6. 高速ETC劝大家不要抬杠:真文案鬼才!
  7. 百度Q1营收241亿,李彦宏挥刀改革:“尽力了”没用,要确保在必须赢的战场上胜利...
  8. 不劳烦苹果了!现在,FBI让嫌疑人抬头刷脸就能解锁iPhone
  9. 1分钟教会你怎么PDF转图片,告别手动截图
  10. 2009福布斯最具潜力中小企业榜
  11. 知网研学+OneDrive实现多电脑文献同步
  12. 表头冻结列冻结_如何在Excel中冻结和取消冻结行和列
  13. juniper设备配置syslog日志发送到远程日志服务器
  14. python实现自动抢课脚本
  15. Cnblogs与Oblog的比较
  16. ABAP 计算时间差
  17. java 求arctan()
  18. 文件监控(二) 代码
  19. 网易邮箱添加html,在网易邮箱中实行添加标签窗口的详细步骤
  20. 使markdown文档中的图片居中

热门文章

  1. Wamp5 配置PHP 图文详解(转)
  2. ecshop 标签使用 非常好的例子
  3. oa 系统后期安装服务
  4. 我喜欢的一首歌--《幸福的瞬间》
  5. 计算机网络管理SIMP,计算机网络管理实验报告.docx
  6. 电子表格转换成数据库_创建数据库,将电子表格转换为关系数据库,第1部分...
  7. leetcode 399. 除法求值(bfs)
  8. leetcode 1024. 视频拼接(dp/贪心)
  9. leetcode1162. 地图分析(bfs)
  10. mooc课程下载_如何使用十大商学院的免费课程制作MOOC“ MBA”