springboot 设置允许跨域的方法

 

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("*");   //允许任何方法
	}
}
发布了33 篇原创文章 · 获赞 23 · 访问量 6596

猜你喜欢

转载自blog.csdn.net/weixin_40516924/article/details/104071818