springboot 设置允许跨域的方法

it2026-06-20  9

1、 @CrossOrigin 注解    // 设置当前controller中的借口 允许 跨域访问

 

 

import org.springframework.web.bind.annotation.CrossOrigin; @CrossOrigin // 设置当前controller中的借口 允许 跨域访问 @RestController public class HelloWorldController { /** * * */ }

 

2、 在启动类中继承WebMvcConfigurerAdapter,重写其中的addCorsMappings方法

package com.example.springbootdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication public class SpringbootdemoApplication extends WebMvcConfigurerAdapter { public static void main(String[] args) { SpringApplication.run(SpringbootdemoApplication.class, args); } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowCredentials(true) .allowedHeaders("*") //允许任何头 .allowedOrigins("*") //允许任何域名 .allowedMethods("*"); //允许任何方法 } }

 

最新回复(0)