SpringBoot解决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" };
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS)
.maxAge(3600);
}
}
2、HTTP请求接口 @RestController
public class HelloController { @Autowired
HelloService 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
*/
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); //
return 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 { @Override
public void init(FilterConfig filterConfig) throws ServletException { } @Override
public 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);
} @Override
public 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”,其实是前端传给后端过来的。如果记不得也没有关系,浏览器的调试器会有详细说明。
來源链接:http://www.jianshu.com/p/e57ed1ee3070
SpringBoot解决ajax跨域问题(转载)的更多相关文章
- SpringBoot解决ajax跨域问题
一.第一种方式: 1.编写一个支持跨域请求的 Configuration import org.springframework.context.annotation.Configuration; im ...
- 如何解决ajax跨域问题(转)
由 于此前很少写前端的代码(哈哈,不合格的程序员啊),最近项目中用到json作为系统间交互的手段,自然就伴随着众多ajax请求,随之而来的就是要解决 ajax的跨域问题.本篇将讲述一个小白从遇到跨域不 ...
- 看小白如何解决ajax跨域问题
由于此前很少写前端的代码(哈哈,不合格的程序员啊),最近项目中用到json作为系统间交互的手段,自然就伴随着众多ajax请求,随之而来的就是要解决ajax的跨域问题.本篇将讲述一个小白从遇到跨域不知道 ...
- 如何解决ajax跨域问题
如何解决ajax跨域问题(转) 由 于此前很少写前端的代码(哈哈,不合格的程序员啊),最近项目中用到json作为系统间交互的手段,自然就伴随着众多ajax请求,随之而来的就是要解决 ajax的跨域问题 ...
- 如何解决Ajax跨域问题-1
如何解决Ajax跨域问题 最近在做AJAX调用C的问题,出现跨域问题,学习总结如下: 在做ajax读取数据的时候,经常会遇到ajax需要跨域的问题,但由于浏览器安全方面的限制,XMLHttpReque ...
- 解决ajax跨域问题的一种方法
解决ajax跨域问题的一种方法 前后端分离经常用json来传输数据,比较常见的问题就有ajax跨域请求的错误问题,这里是我的一种解决方法: 在java中加入如下的注解类: import org.spr ...
- 【前端_js】解决ajax跨域请求数据
1.ajax发送请求必须遵循同源策略,即请求方和相应方的协议头.域名.端口全部一样.只要三者有一个不一样都视为跨域,浏览器出于安全考虑不允许跨域访问. 解决ajax跨域访问的常用方法: a.使用jso ...
- 谷歌浏览器解决ajax跨域问题
在用mui和H5+做混合开发,会利用HBuildx去真机调试,可真机调试总有问题所在,懂得人自然懂,而我们直接打开页面显示的只有一个静态的页面,是获取不到数据的在这里我想说的不是代码中利用jsonp, ...
- 如何解决ajax跨域请求?
1.什么是跨域? a.域名不同 b.域名相同,端口不同 注:只有域名相同,端口相同时,才可以访问数据 可以使用jsonp解决ajax跨域请求的问题. 2.什么是jsonp? Jsonp其实就是一个跨域 ...
随机推荐
- Redis05——Redis高级运用(管道连接,发布订阅,布隆过滤器)
Redis高级运用 一.管道连接redis(一次发送多个命令,节省往返时间) 1.安装nc yum install nc -y 2.通过nc连接redis nc localhost 6379 3.通过 ...
- Satellite-Hacking 攻击卫星/卫星安全
虽说卫星安全这种东西也是高富帅才玩得起的领域,但是了解了解总是没坏处.参考了一些资料,如果想详细了解可以戳进去看看.看了这么多资料,总结一下吧. Why? 卫星存在安全问题主要有一下俩原因,首先是成本 ...
- 一文透彻掌握 Python 编码问题
一.当我说字符时,我在说什么? 当我们提起字符串时,每个程序员都能理解到,我们说的是一个字符序列.但是,当我们说字符时,很多人就困惑了. 写在纸上的字符很容易辨识,但是为了将不同的字符在计算机中标识出 ...
- ULPFEC在WebRTC中的实现[转载]
一.WebRTC对抗网络丢包的两种手段 丢包重传(NACK)和前向纠错(FEC).FEC是一种前向纠错技术,发送端将负载数据加上一定的冗余纠错码一起发送,接收端根据接收到的纠错码对数据进行差错 ...
- Mac下 CMD常用命令
1.常用命令 pwd 当前工作目录 cd(不加参数) 进root cd(folder) 进入文件夹 cd .. 上级目录 cd ~ 返回root cd - 返 ...
- 解决tomcat控制台乱码+清除过期缓存条目后可用空间仍不足 - 请考虑增加缓存的最大空间问题
一.乱码 1.打开Tomcat的目录,找到conf文件夹,一般修改server.xml中的编码集,改为utf-8即可 2.若server.xml中编码设置的就是utf-8,可以修改logging.pr ...
- Object-C(自学1)
----- 需求索要 自学了下 OBJECt-C ----- 就基础部分一些 和操作 command + R 运行command +B 只编译.m文件 NSlog() = printfNSLog 是 ...
- 【Winfrom-禁止重复启动程序】 程序不能重复启动
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Sy ...
- The Cost of JavaScript --------引用
tl;dr: 想要保持页面的快速运行,你需要仅加载当前页面所需的 JavaScript 代码.优先考虑用户所需,之后运用代码分离懒加载其他内容. Is it happening - 在这个时期,你可以 ...
- C# Lambda表达式学习笔记
本笔记摘抄自:https://www.cnblogs.com/leslies2/archive/2012/03/22/2389318.html,记录一下学习过程以备后续查用. 一.Lambda ...