axios 官网:http://axios-js.com/
现在项目控制台的根目录下载 axios :npm install axios(如果使用 yarn 包管理器,也可以:yarn add axios)
下载成功后 package.json 会添加 axios 的相关版本信息:
新建文件夹 plugins ,并在里面新建 js 文件:myAxios.js
import axios from "axios";
// 定义 axios
const myAxios = axios.create({
baseURL: 'http://localhost:8080/api' // 发给后端统一的请求地址
});
// 前端向后台发请求
myAxios.interceptors.request.use(function (config) {
console.log("我要发请求了", config)
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// 接受后台的请求
myAxios.interceptors.response.use(function (response) {
console.log("我收到你的响应啦", response)
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
export default myAxios;
前端发请求的代码:
<template>
</template>
<script setup>
import myAxios from "../plugins/myAxios.js";
onMounted(() => {
myAxios().get('/testUrl', { // /testUrl 为请求的路径
params: {
ID: 12345 // ID 为要传入的参数
}
})
.then(function (response) { // 成功执行的方法
console.log(response);
showToast.success('请求成功')
})
.catch(function (error) { // 失败执行的方法
console.error("/user/search/tags error", error);
})
.then(function () { // 这个 then 无论相应成功或失败都会执行
});
})
</script>
<style scoped>
</style>
这时候在前端代码发出请求的时候可能会遇到跨域问题:
(跨域问题:当目的地址、发送请求到的服务器地址、域名、端口号...不一致的时候就会出现跨域问题)
后端用 SpringBoot 框架的时候,直接在接收请求的 Controller 类中加上注解 @CrossOrigin (import java.util.stream.Collectors;)
为了安全 可以在注解后加上内容
(origins = {"http://localhost:5173/"}) // 前端地址 端口号注意填写自己的前端的端口号
这时候就可以啦