一,gateway网关跨域
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
@Configuration
public class AppConfig {
@Bean
public CorsWebFilter corsWebFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
二,springboot跨域
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*");
}
};
}
}
三,servlet跨域文章来源:https://www.toymoban.com/news/detail-673533.html
注意如果传了自定义header,需要覆盖doOptions方法,因为传自定义header后浏览器在发起请求前会发送一个options请求(chrome的开发工具看不到options请求,edge浏览器可以看到),不覆盖doOptions可以在edge的开发工具中看到options的响应码是403造成跨域失败:文章来源地址https://www.toymoban.com/news/detail-673533.html
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetArchive3dData extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doOptions(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
// 允许所有域名的跨域请求
response.setHeader("Access-Control-Allow-Origin", "*");
// 允许特定的请求方法
response.setHeader("Access-Control-Allow-Methods", "*");
// 允许特定的请求头
response.setHeader("Access-Control-Allow-Headers", "*");
PrintWriter out = response.getWriter();
out.print("跨域请求返回的内容");
out.flush();
out.close();
}
}
到了这里,关于gateway网关、Springboot、Servlet跨域的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!