欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot 设置允许跨域的方法

程序员文章站 2022-07-09 22:32:06
...

 

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("*");   //允许任何方法
	}
}

 

相关标签: 后端笔记