版本说明
springboot 2.7.17
- 原来代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigin("*")
.allowCredentials(true);
}
}
- controller层代码
@RestController
public class SendController {
@RequestMapping("/send")
public ArrayList<Work> send() {
ArrayList<Work> list = new ArrayList<>();
Work work1 = new Work(1, "骆驼祥子", "老舍", "文学", "无");
Work work2 = new Work(2, "红楼梦", "曹雪芹", "文学", "无");
Work work3 = new Work(3, "活着", "余华", "文学", "无");
Work work4 = new Work(4, "西游记", "施耐庵", "文学", "无");
list.add(work1);
list.add(work2);
list.add(work3);
list.add(work4);
return list;
}
}
- 前端代码(部分)
<script setup>
import { ref} from "vue";
import axios, { Axios } from "axios";
const list = ref([]);
const title = "hello world";
const send = function() {
console.log('hello');
axios.get('http://localhost:8080/send')
.then((res=>{
console.log(res.data);
list.value = res.data;
console.log(list.value);
}))
.catch((err=>{
console.log(err);
}))
}
</script>
<template>
<button @click="send">点击发送axios请求</button>
<table border="1" v-for="(item) in list" :key="item.id">
<tr>
<th style="color: brown;">序号</th>
<th>文章</th>
<th>作者</th>
<th>类型</th>
<th>备注</th>
</tr>
<tr>
<td>{{ item.id }}</td>
<td>{{ item.title }}</td>
<td>{{ item.author }}</td>
<td>{{ item.type }}</td>
<td>{{ item.other }}</td>
</tr>
</table>
</template>
-
现象
- 前端
- 前端点击click发生跨域问题
- 后端抛出异常
-
查看异常
java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
- 解析异常
When allowCredentials is true,allowedOrigins cannot contain the special value "*"
To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
- 解决
- 使用allowedOriginPatterns代替allowedOrigins
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*") // 这里
.allowCredentials(true);
}
}
- 重启服务,再次点击button,得到数据