springboot-web 应用开发-CORS 支持跨域访问

跨域访问技术CORS

在 spring MVC 中可以配置全局的规则,也可以使用@CrossOrigin 注解进行细粒度的配置。

1.全局配置:

@Configuration
public class CustomCorsConfiguration {
	  @Bean
	  public WebMvcConfigurer corsConfigurer() {
	     return new WebMvcConfigurerAdapter() {
	         @Override
	         public void addCorsMappings(CorsRegistry registry) {
	              registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
	 } };
 } }

或者
@Configuration
public class CustomCorsConfiguration2 extends WebMvcConfigurerAdapter {
  
  @Override
  public void addCorsMappings(CorsRegistry registry) {
     registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
  }
  }
或者
@RestController
@RequestMapping("/api")   
public class ApiController {
  @RequestMapping(value = "/get",method = RequestMethod.POST)

  @CrossOrigin(origins = "http://localhost:8099")  //跨域项目路径
  public HashMap<String, Object> get(@RequestParam String name) {
     HashMap<String, Object> map = new HashMap<String, Object>();
     map.put("title", "hello world");
     map.put("name", name);
     return map;
 } }

2.定义controller

@RestController
@RequestMapping("/api")
public class ApiController {
  @RequestMapping(value = "/get")
  public HashMap<String, Object> get(@RequestParam String name) {
     HashMap<String, Object> map = new HashMap<String, Object>();
     map.put("title", "hello world");
     map.put("name", name);
     return map;
 } }

3.filter中设置请求头,防止请求被拦截

@Override
  public void doFilter(ServletRequest request, ServletResponse sresponse, FilterChain chain)
         throws IOException, ServletException {

      HttpServletResponse response = (HttpServletResponse) sresponse;
      //跨域访问不拦截请求
      response.setHeader("Access-Control-Allow-Origin", "*");
        chain.doFilter(request, response);
}

4.其他项目前端ajax

  <script>
		$(function(){
			$('#title').click(function(){
				alert('点击了');
                $.ajax({
                    url: "http://localhost:8090/api/get",  //跨域url
                    type: "POST",
                    data: {
                        name: "测试" },
                    success: function(data, status, xhr) {
                        console.log(data);
                        alert(data.name);
                    } });
			});
		})
	</script>

猜你喜欢

转载自blog.csdn.net/weixin_42465206/article/details/89100938
今日推荐