SpringBoot解决ajax跨域问题的方法

网友投稿 269 2023-02-14


SpringBoot解决ajax跨域问题的方法

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()); // 4

return new CorsFilter(source);

}

}

2、indeYdjoNaIx.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 fYdjoNaIilterConfig) 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”,其实是前端传给后端过来的。如果记不得也没有关系,浏览器的调试器会有详细说明。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:api接口在线管理文档(API接口管理)
下一篇:写一个移动端惯性滑动&回弹Vue导航栏组件 ly
相关文章

 发表评论

暂时没有评论,来抢沙发吧~