Vue3 + Vite 开发环境下解决跨域问题:配置代理服务器
一、介绍
在 Vue3
结合 Vite
的前端开发中,跨域问题是常见的挑战之一。特别是在开发阶段,当后端 API 尚未配置好 CORS
支持时,使用代理服务器来绕过浏览器的同源策略(Same-origin policy)就显得尤为重要。本文将介绍如何在 Vite
中配置代理服务器,并展示一个简单的示例。
二、场景描述
当前端要调用服务器端的 API 接口,而服务器端没有配置 CORS (Cross-Origin Resource Sharing)
,此时可能会使用代理服务器来解决跨域问题。在生产环境,可能会使用Nginx来作为代理服务器;在开发环境,Vue3中可以配置内置的HTTP服务器作为代理,将请求通过代理服务器发送到目标服务器,而浏览器只会看到来自代理服务器的响应,这就可以绕过同源策略的限制。
三、配置代理服务器(开发环境)
使用代理:在开发环境中,可以在 Vite
的配置文件中设置代理服务器。在vite.config.js
中配置代理服务器,将请求转发到目标服务器。
- 在项目根目录下修改
vue.config.js
文件。 - 在此文件中配置代理规则。
配置代理服务器(vite.config.js)
// 配置服务器的代理设置server: {// 代理配置,用于重定向请求到其他服务器proxy: {// 定义一个代理规则,将/hello-world路径下的请求代理到指定的目标服务器'/hello-world': {// 目标服务器的地址target: 'http://localhost:8080',// 更改请求的origin为代理服务器的origin,以便与目标服务器交互changeOrigin: true,// 重写请求路径,移除/hello-world前缀rewrite: (path) => path.replace(/^\/hello-world/, '')}}}
vite.config.js 代码示例
import { fileURLToPath, URL } from 'node:url'import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'// https://vitejs.dev/config/
export default defineConfig({plugins: [vue(),],resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url))}},// 配置服务器的代理设置server: {// 代理配置,用于重定向请求到其他服务器proxy: {// 定义一个代理规则,将/hello-world路径下的请求代理到指定的目标服务器'/hello-world': {// 目标服务器的地址target: 'http://localhost:8080',// 更改请求的origin为代理服务器的origin,以便与目标服务器交互changeOrigin: true,// 重写请求路径,移除/hello-world前缀rewrite: (path) => path.replace(/^\/hello-world/, '')}}}
})
四、Axios调用接口
App.vue
中,通过 Axios
调用接口。
<script setup>
import axios from 'axios';async function queryUsers() {try {const response = await axios.get(`/hello-world/users`);// 如果请求成功,处理响应数据if (response.status === 200) {console.log('请求成功:', response.data);} else {console.error('请求失败, 状态码:', response.status);}} catch (error) {console.error('请求异常:', error);}
}
</script><template><button class="my-button" @click="queryUsers">查询用户列表</button>
</template><style scoped>
.my-button {background-color: #007bff;/* 可根据需要自定义颜色 */color: white;padding: 0.5rem 1rem;border: none;border-radius: 0.25rem;cursor: pointer;margin-top: 1rem;
}.my-button+.my-button {/* 适合的间距值 */margin-left: 0.5rem;
}
</style>
在这个示例中,我们定义了一个名为 queryUsers
的函数,它通过 Axios
发起 GET 请求,并且在按钮点击事件中调用这个函数。
五、接口调用效果
1. 浏览器直接调用接口(不存在跨域问题)
当在浏览器中直接访问 API 时,由于请求直接从客户端发出,因此不会遇到跨域问题。
2. Axios接口调用(未配置代理服务器)
如果尝试从前端应用直接向未配置 CORS
的后端服务发起请求,则会因为跨域策略而被阻止:
Access to XMLHttpRequest at ‘http://localhost:8080/users’ from origin ‘http://localhost:5173’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
跨域报错代码如下:
<script setup>
import axios from 'axios';async function queryUsers() {try {const response = await axios.get(`http://localhost:8080/users`);// 如果请求成功,处理响应数据if (response.status === 200) {console.log('请求成功:', response.data);} else {console.error('请求失败, 状态码:', response.status);}} catch (error) {console.error('请求异常:', error);}
}
</script>
3. Axios接口调用(配置代理服务器)
当正确配置了代理服务器之后,前端应用能够顺利地通过代理向后端 API 发送请求,并获取响应数据。