目录
1. 添加 Controller 层:调用 userService 中之前写好的 searchUsersByTags() 来根据前端传来的标签搜索过滤数据库中的用户
/**
* 根据标签搜索用户
* @param tagNameList 标签列表
* @return 搜索到的用户列表
*/
@GetMapping("/search/tags")
public BaseResponse<List<User>> searchUsersByTags(@RequestParam(required = false) List<String> tagNameList) {
if(CollectionUtils.isEmpty(tagNameList)) {
throw new BusinessException(ErrorCode.PARAMS_ERROR);
}
List<User> userList = userService.searchUsersByTags(tagNameList);
return ResultUtils.success(userList);
}
2. 启动项目,测试接口
数据库暂时只有一个用户有标签信息,所以响应数据的用户列表只有一个用户
整合 Axios
npm install axios
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
Access to XMLHttpRequest at 'http://localhost:8080/api/user/search/tags' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
?
@CrossOrigin(poigins = { "http://user.zhulang-user-center.top" }, methods = { RequestMethod.POST })
import {onMounted, ref} from "vue";
import myAxios from "/src/plugins/myAxios.js";
import qs from 'qs';
const { tags } = route.query;
onMounted( () => {
myAxios.get('/user/search/tags', {
params: {
tagNameList: tags,
},
paramsSerializer: params => {
return qs.stringify(params, {indices: false})
}
})
.then(function (response) {
// handle success
console.log("/user/search/tags succeed", response);
})
.catch(function (error) {
// handle error
console.log("/user/search/tags error", error);
})
.then(function () {
// always executed
});
})
http://localhost:8080/api/user/search/tags?tagNameList=%E7%94%B7
<script setup lang="ts">
import { useRoute } from'vue-router'
import {onMounted, ref} from "vue";
import myAxios from "/src/plugins/myAxios.js";
import qs from 'qs';
import type {UserType} from "@/models/user";
const route = useRoute();
const { tags } = route.query;
const userList = ref([]);
onMounted( async () => {
const userListData: UserType[] = await myAxios.get('/user/search/tags', {
params: {
tagNameList: tags,
},
paramsSerializer: params => {
return qs.stringify(params, {indices: false})
}
})
.then(function (response) {
// handle success
console.log("/user/search/tags succeed", response);
return response.data?.data;
})
.catch(function (error) {
console.log("/user/search/tags error", error);
})
if(userListData) {
userList.value = userListData;// userListData 存在则赋给 userList 进行展示
}
})
</script>
问题:后端保存的标签 tags 是 JSON?字符串格式,前端把每个字符都解析成了一个数组元素,即每个字符都被解析成了一个标签
if(userListData) {
userListData.forEach(user => {
if(user.tags) {
user.tags = JSON.parse(user.tags);
}
});
userList.value = userListData;
}
<van-empty image="search" description="暂无符合要求的用户" />
什么是跨域?
- 浏览器的安全问题,仅允许向同协议、同域名、同端口的服务器发送请求
- 前后端交互时有一个不同都会引起跨域
# 跨域配置
location ^~ /api/ {
proxy_pass http://127.0.0.1:8080/api/;
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers '*';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
}
SpringBoot 项目直接在接口首部加上注解 @CrossOrigin 表示允许跨域即可
后端支持跨域的好处
灵活管理多个前端的不同跨域限制:如允许域名 A 的 GET 请求跨域,域名 B 的POST 请求跨域
后端统一管理更加安全
前端不用反复写跨域配置