zoukankan      html  css  js  c++  java
  • SpringBoot 中通过 CORS 解决跨域问题

    同源策略

    源(origin)就是协议(http)、域名(localhost)和端口号(8080),同源是指协议、域名以及端口要相同。

    No 'Access-Control-Allow-Origin' header is present on the requested resource.

    后端使用CORS(跨域源资源共享)(CORS,Cross-origin resource sharing)实现跨域

    • 全局配置
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")  //允许跨域的路径
            .allowedOrigins("*")  //允许的所有域名
            //.allowedOrigins("http://localhost:8081")  //允许的指定域名
            .allowedMethods("*")   //允许的方法
            .allowedHeaders("*");  //允许的请求头
        }
    }
    • 局部配置
      • 在方法上
    @RestController
    public class HelloController {
        @CrossOrigin(value = "http://localhost:8081")
        @GetMapping("/hello")
        public String hello() {
            return "hello";
        }
    
        @CrossOrigin(value = "http://localhost:8081")
        @PostMapping("/hello")
        public String hello2() {
            return "post hello";
        }
    }
      • 在Controller上
    @RestController
    @CrossOrigin(value = "http://localhost:8081")
    public class HelloController {
        @GetMapping("/hello")
        public String hello() {
            return "hello";
        }
    
        @PostMapping("/hello")
        public String hello2() {
            return "post hello";
        }
    }
  • 相关阅读:
    SA(后缀数组)专题总结
    LCT总结
    多项式全家桶
    fft.ntt,生成函数,各种数和各种反演
    P3939 数颜色
    P1879 [USACO06NOV]玉米田Corn Fields
    主席树模板
    P2633 Count on a tree
    P1972 [SDOI2009]HH的项链
    数论
  • 原文地址:https://www.cnblogs.com/zxg-6/p/12315301.html
Copyright © 2011-2022 走看看