Vite本地开发调用外部API遇CORS问题,寻求解决方案
CORS问题:Vite+React项目中POST/DELETE请求失败的解决
问题详情
我正在用TanStack、axios、React和Vite开发应用,所有GET请求正常,但POST/DELETE请求因CORS问题失败。目标API已设置Access-Control-Allow-Origin: *,但了解到通配符源下,POST/PUT/DELETE请求需要本地开发服务器指定响应源。
已尝试的操作:
- 在vite.config中将
cors设为false - 给配置对象添加允许的源
- 为axios请求添加不同请求头
用ThunderClient测试时,POST/DELETE请求均正常,求后续排查方向。
已尝试的代码配置
Vite配置文件
export default defineConfig({ plugins: [react()], server: { open: '/index.html', cors: false }, })
TanStack Mutation的POST请求代码
const { mutate } = useMutation({ mutationFn: async (newStation: Station): Promise<Station> => { return await axios.post( `http://api.openweathermap.org/data/3.0/stations?appid=API_KEY`, newStation, { headers: { 'Content-Type': 'application/json', }, } ); }, onSuccess: (data) => { queryClient.setQueryData(['weatherStations', data.id], data); queryClient.invalidateQueries(['weatherStations'], { exact: true }); }, });
CORS错误截图

最终解决方法
步骤1:修改Vite配置,添加代理
在vite.config.js的server配置中新增代理规则:
export default defineConfig({ plugins: [react()], server: { open: '/index.html', proxy: { "/weather/api": { target: "http://api.openweathermap.org/", changeOrigin: true, rewrite: (path) => path.replace(/^\/weather\/api/, ''), } } }, })
步骤2:调整axios请求路径
将请求的目标地址替换为代理前缀路径,以DELETE请求为例:
await axios.delete(`/weather/api/data/3.0/stations/${id}?appid=API_KEY`, { headers: { 'Content-Type': 'application/json', }, });
核心原理
CORS限制是浏览器的安全机制,仅作用于浏览器客户端与服务器的直接请求。通过Vite代理,让本地开发服务器作为中转转发请求到目标API,此时请求变为服务器间通信,不受浏览器CORS校验限制,从而解决问题。
内容的提问来源于stack exchange,提问作者J4v4Scr1pt
相关产品推荐
相关产品推荐

