在vue中解决请求跨域问题
2024年12月9日小于 1 分钟
在vue中解决请求跨域问题
1.基于vite构建
1.1 配置代理
在配置文件和组件的具体请求路径中,进行路径拼接
如果没有使用pathRewrite则代表直接代理地址后拼接原始前端路径 例如:前端接口路径 /api/user/login ====> https://tcsday.com/api/user/login
如果使用了pathRewrite,则在原来的基础上去掉/api 例如:/api/user/login ====> https://tcsday.com/user/login
export default defineConfig({
server: {
proxy: {
'/api': {
target: 'https://tcsday.com',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
},
}
}
})
1.2 组件拼接完整路径
<script setup lang="ts">
import axios from "axios";
axios.post("/api/weather?name=贺州市").then((res) => {
console.log(res.data);
})
</script>