Springboot 解决跨域请求

Cors处理 跨域请求

细粒度

直接在controller层上 添加@CrossOrigin注解

@PostMapping("/")
@CrossOrigin(value = "http://localhost:8081", maxAge = 1800, allowedHeaders = "*")
public String addBook(String name) {
  System.out.println("receive: " + name);
  return "receive: " + name;
}

粗粒度

写一个config类, addMapping 即需要处理的url请求

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/book/**")
        .allowedHeaders("*")
        .allowedMethods("*")
        .maxAge(1800)
        .allowedOrigins("http://localhost:8008");
  }
}

猜你喜欢

转载自www.cnblogs.com/Draymonder/p/11824838.html