當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot解决ajax跨域问题
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot解决ajax跨域问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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跨域问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 整理iOS9适配中出现的坑
- 下一篇: 个人博客作业_week2