springboot跨域

来源:互联网 发布:医院挂号哪个软件好 编辑:程序博客网 时间:2024/06/11 00:08

目录

    • 目录
  • springboot跨域
    • 第一种方式全局配置
      • 1
      • 2
    • 第二种细粒度控制

springboot跨域

第一种方式:全局配置

1

/** * 全局设置 * @author wujing */@Configurationpublic class CustomCorsConfiguration {    @Bean    public WebMvcConfigurer corsConfigurer() {        return new WebMvcConfigurerAdapter() {            @Override            public void addCorsMappings(CorsRegistry registry) {                // 限制了路径和域名的访问            registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");            }        };    }

2

/*** 全局设置** @author wujing*/@Configurationpublic class CustomCorsConfiguration2 extends WebMvcConfigurerAdapter {    @Override    public void addCorsMappings(CorsRegistry registry) {        registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");    }}

第二种:细粒度控制

@CrossOrigin(origins = "http://localhost:8080")在controller里

@RestController@RequestMapping(value = "/api", method = RequestMethod.POST)public class ApiController {    @CrossOrigin(origins = "http://localhost:8080")    @RequestMapping(value = "/get")    public HashMap<String, Object> get(@RequestParam String name) {        HashMap<String, Object> map = new HashMap<String, Object>();        map.put("title", "hello world");        map.put("name", name);        return map;    }}
原创粉丝点击