SpringBoot in solving problems through cross-domain CORS

Same Origin Policy

Source (origin) is the protocol (http), domain name (localhost) and port number (8080), homology means the agreement, as well as the port to the same domain name.

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

Backend CORS (cross-domain resource sharing source) (CORS, Cross-origin resource sharing) cross-domain

  • Global Configuration
@Configuration
 public  class WebMvcConfig the implements WebMvcConfigurer { 
    @Override 
    public  void addCorsMappings (CorsRegistry Registry) { 
        registry.addMapping ( "/ **")   // allow cross-domain path 
        .allowedOrigins ( "*")   // Allow all domain names
         // .allowedOrigins ( " HTTP: // localhost : 8081")   // allow specified domain 
        .allowedMethods ( "*")    // allowedMethod 
        .allowedHeaders ( "*");   // allow the request header 
    } 
}

 

  • Local Configuration
    • Methodologically
@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";
    }
}

 

    • On the 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";
    }
}

Guess you like

Origin www.cnblogs.com/zxg-6/p/12315301.html