You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js 3本地调用第三方API遭遇CORS问题求助

Vue3 + Vite项目CORS问题排查与解决

一、核心问题:Vite配置文件误用

你当前使用的vue.config.js是Vue CLI的配置文件,Vue3 + Vite项目不识别该文件,必须改用vite.config.js(根目录创建),正确代理配置如下:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  server: {
    proxy: {
      '/api': {
        target: 'https://ded.austory.it',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '') // 移除请求路径中的/api前缀
      }
    }
  }
})

二、调整环境变量与Axios配置

  1. 修改.env.development中的环境变量:
VITE_APP_API_URL="/api"
  1. 确保Axios实例绑定正确的baseURL:
    在ApiService初始化代码中添加:
ApiService.vueInstance.axios.defaults.baseURL = import.meta.env.VITE_APP_API_URL;

此时调用ApiService.post("/login", credentials),实际请求会指向http://localhost:5173/api/login,再通过代理转发到目标API地址。

三、为什么keenthemes的API能正常调用?

该API的后端服务器配置了宽松的CORS策略(比如返回Access-Control-Allow-Origin: *),允许任意前端域名发起请求,因此直接调用不会触发CORS错误。而你的目标APIhttps://ded.austory.it未配置允许http://localhost:5173(本地开发域名)的CORS规则,直接请求会被浏览器拦截。

四、额外排查步骤

  1. 修改配置后必须重启Vite开发服务器,否则配置不生效。
  2. 打开浏览器开发者工具,确认请求地址为localhost:5173/api/login,而非直接请求目标API域名。
  3. 若代理方案无法使用,需后端在https://ded.austory.it服务器上配置CORS:
    • 允许Origin为http://localhost:5173(生产环境需指定具体业务域名)
    • 允许POST、OPTIONS等请求方法
    • 允许自定义请求头(如token、Content-Type等)

内容的提问来源于stack exchange,提问作者pankaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 16:31:00