Vue3 配置 vite.config.js 解决跨域问题
问题
Access to XMLHttpRequest at ‘http://localhost:8080/user/register’ from origin ‘http://localhost:5173’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
解决
原 request.js
// 导入 axios 依赖
import axios from 'axios';
// 定义baseUrl
const baseURL = 'http://localhost:8080';
// 创建实例
const instance = axios.create({
baseURL: baseURL,
});
// 添加响应拦截器
instance.interceptors.response.use(
result => {
return result.data;
},
err => {
alert("服务异常");
return Promise.reject(err);
}
)
export default instance;
修改 request.js
// 导入 axios 依赖
import axios from 'axios';
// 定义baseUrl
const baseURL = '/api';
// 创建实例
const instance = axios.create({
baseURL: baseURL,
});
// 添加响应拦截器
instance.interceptors.response.use(
result => {
return result.data;
},
err => {
alert("服务异常");
return Promise.reject(err);
}
)
export default instance;
注意: rewrite: (path) => path.replace(/^/api/, “”) 中 /^/api/ 不要加引号