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

VueJS中使用Axios调用Open API出现跨域请求阻塞问题求助

解决VueJS中Axios调用Trefle API的跨域问题

先修正你代码中的无效配置项

你的Axios配置里存在几个关键错误,直接导致请求异常或跨域问题:

  1. mode: 'no-cors':这是Fetch API的专属配置,Axios不支持该参数。即便强行套用,浏览器会返回无法读取内容的opaque响应,你根本拿不到任何数据。
  2. Access-Control-Allow-Origin: *:这是服务器端需要返回的响应头,不是前端请求头。前端手动添加这个请求头不仅无效,还可能干扰正常请求逻辑。
  3. baseURL包含完整查询参数:把?token=xxx直接写在baseURL里,会导致后续get()调用时URL参数拼接错误,同时不符合Axios的配置规范。

修正后的Axios实例配置:

const axiosInstance = axios.create({
  baseURL: 'https://trefle.io/api/v1',
  headers: {
    'Content-Type': 'application/json',
  },
  params: {
    token: '********' // 将token作为默认请求参数
  }
})

async getPlantsList(context) {
  try {            
    const response = await axiosInstance.get('/plants');
    console.log('2', response.data);
  } catch(error) {
    console.log('error', error);
  }
}

解决跨域的核心方案

跨域问题的本质是浏览器同源策略限制,前端无法直接绕过,必须通过以下两种方式解决:

方案一:Vue CLI本地代理(开发环境)

如果你的项目是Vue CLI创建的,可以配置本地代理,让浏览器请求本地服务器,再由本地服务器转发请求到Trefle API,从而规避跨域限制:

  1. 在项目根目录创建vue.config.js文件,添加代理配置:
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'https://trefle.io/api/v1',
        changeOrigin: true, // 开启跨域转发
        pathRewrite: {
          '^/api': '' // 重写路径,把/api替换为空
        }
      }
    }
  }
}
  1. 修改Axios实例的baseURL为代理路径:
const axiosInstance = axios.create({
  baseURL: '/api',
  headers: {
    'Content-Type': 'application/json',
  },
  params: {
    token: '********'
  }
})

方案二:服务器端代理(生产环境)

生产环境不能依赖Vue CLI的本地代理,需要自己搭建一个简单的后端服务(比如Node.js、PHP等)作为中间层转发请求:
以Node.js Express为例,搭建代理接口:

const express = require('express');
const axios = require('axios');
const app = express();

app.get('/api/plants', async (req, res) => {
  try {
    const response = await axios.get('https://trefle.io/api/v1/plants', {
      params: {
        token: '********',
        ...req.query // 传递前端的其他查询参数
      }
    });
    res.json(response.data);
  } catch (error) {
    res.status(error.response.status).json(error.response.data);
  }
});

app.listen(3001, () => {
  console.log('Proxy server running on port 3001');
});

之后前端Axios的baseURL改为http://localhost:3001/api即可。

额外说明

如果上述方案都无效,需要查看Trefle API的官方文档:部分API为了安全,仅允许服务器端调用(不支持前端CORS请求),这种情况下必须使用服务器端代理,无法直接从前端发起请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:05:19