Spring Boot Web应用开发 CORS 跨域请求设置 Invalid CORS request

2022-07-04 11:28:23

使用SpringBoot Web开发程序时,前后端分离时,经常遇到跨域问题,特别是很多情况下Firefox浏览器没有问题,而chrome浏览器有问题,仅仅从浏览器的web控制台很难发现有效的错误或者告警信息,因此在开发程序很有必要在开发阶段就考虑到并配置好跨域。

SpringBoot提供的跨域配置有两种,一种是全局的,一种是具体到方法的。如果同时配置了那么具体方法的优先。
具体代码在这里欢迎fork,加星。

全局跨域配置
直接上代码,也就提供一个自定义的WebMvcConfigurer bean,该bean的addCorsMappings方法中定义自己的跨域配置。
可以看到我的跨域配置是允许来自http://localhost:6677访问/user/users/*的方法。等程序运行后我们可以发现如果我们的前端使用http://127.0.0.1:6677 或者我们的前端运行在http://localhost:8080都无法通过rest访问对应的API(备注,示例程序提供了/user/users和/user/users/{userId}方法)

package com.yq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
public class CorsDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(CorsDemoApplication.class, args);
	}

	@Bean
	public WebMvcConfigurer corsConfigurer() {
		return new WebMvcConfigurerAdapter() {
			@Override
			public void addCorsMappings(CorsRegistry registry) {
				registry.addMapping("/user/users/*").allowedOrigins("http://localhost:6677");
			}
		};
	}
}

具体方法的跨域配置@CrossOrigin
我们可以使用@CrossOrigin在具体的API上配置跨域设置。@CrossOrigin(origins = “http://localhost:9000”)表明该方法允许来自http://localhost:9000访问,也就是前端可以是localhost:9000。

    @ApiOperation(value = "查询所有用户")
    @CrossOrigin(origins = "http://localhost:9000")
    @GetMapping(value = "/users", produces = "application/json;charset=UTF-8")
    public Iterable<User> findAllUsers() {
        Collection<User> users = userMap.values();
        return users;
    }

前端代码
前端一个简单的js和html,详细内容看代码

$(document).ready(function() {
    $.ajax({
        url: "http://localhost:6606/user/users/2"
    }).then(function(data, status, jqxhr) {
       console.log(data);
       $('.user-id').append(data.id);
       $('.user-name').append(data.name);
       console.log(jqxhr);
    });
});

效果截图。
示例程序前后端在一起。都运行本机的6606端口上,当你使用http://127.0.0.1:6606/时,因为跨域设置不对,前端无法访问http://localhost:6606/user/users/2。 当前段运行在http://localhost:6677/时,前端可以正常访问http://localhost:6606/user/users/2
在这里插入图片描述

  • 作者:russle
  • 原文链接:https://blog.csdn.net/russle/article/details/83045859
    更新时间:2022-07-04 11:28:23