服务端解决浏览器跨域问题

1 简单跨域GET,POST 在方法中加上  response.addHeader("Access-Control-Allow-Origin","http://localhost:8080"); 第二个参数是允许跨域的服务器

eg:

@GetMapping("/stock/getIpAndPort")
public String getIpAndPort(HttpServletResponse response) {
response.addHeader("Access-Control-Allow-Origin","http://localhost:8080");
return "127.0.0.1:9999";
}

2 对于Spring boot 项目 可以在启动类添加 bean
eg:

//    复杂跨域问题(两次握手)
@Bean
public WebMvcConfigurer corsConConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
          //allowedOrigins里面的参数为允许访问的ip地址
            }
};
}



 

posted @ 2020-07-15 09:31  tomsen_jin  阅读(311)  评论(0编辑  收藏  举报