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

使用API获取数据时遭遇CORS错误,求解决方案

解决CORS错误的方案

先看你代码里的明显问题:URL重复嵌套了两次https://cors-anywhere.herokuapp.com/,这会导致请求路径异常,先修正为单一层代理:

useEffect(() => {
  if (props.product_id) {
    axios
      .get(`https://cors-anywhere.herokuapp.com/https://51fgc922b7.execute-api.ap-south-1.amazonaws.com/dev/productpreview?product_id=${props.product_id}`)
      .then((res) => {
        console.log(res.data.data)
        setModelData(res.data.data[0])
      })
      .catch((error) => {
        setIsErrorImage(true)
      })
  }
}, []);

注意:公共CORS代理如cors-anywhere有使用限制,你需要先访问其主页点击"Request temporary access to the demo server"获取临时授权,才能正常发起请求。

以下是更可靠的长期解决方案:

  • 后端配置CORS(最优解)
    若你能控制目标AWS API Gateway的配置,直接在API Gateway中开启CORS规则:

    1. 进入AWS控制台的API Gateway服务,找到productpreview资源
    2. 点击"Actions" -> "Enable CORS"
    3. 设置Access-Control-Allow-Origin为你的前端域名(开发环境可临时用*,生产环境建议指定具体域名)
    4. 允许需要的HTTP方法(此处为GET)和请求头,保存后重新部署API
      配置完成后,前端直接请求原API地址即可,无需代理。
  • 开发环境本地代理
    React项目可通过配置本地代理绕过CORS:

    1. 在项目根目录的package.json中添加:
      "proxy": "https://51fgc922b7.execute-api.ap-south-1.amazonaws.com"
      
    2. 修改请求代码为相对路径:
      axios.get(`/dev/productpreview?product_id=${props.product_id}`)
      

    开发环境下React会自动将请求代理到目标API,规避CORS错误。

  • 自行部署CORS代理
    公共代理不稳定且有风险,你可以用Node.js快速搭建专属代理并部署:
    示例代码(基于express):

    const express = require('express');
    const cors = require('cors');
    const axios = require('axios');
    
    const app = express();
    app.use(cors());
    
    app.get('/productpreview', async (req, res) => {
      try {
        const response = await axios.get(`https://51fgc922b7.execute-api.ap-south-1.amazonaws.com/dev/productpreview?product_id=${req.query.product_id}`);
        res.send(response.data);
      } catch (err) {
        res.status(err.response?.status || 500).send(err.response?.data || 'Proxy error');
      }
    });
    
    app.listen(3001, () => console.log('CORS proxy running on port 3001'));
    

    部署后,前端请求该代理地址即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:05:31