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

React集成FedEx时遭遇CORS错误求助

问题描述

在React项目中集成FedEx API时遇到以下问题:

  • 可通过谷歌浏览器插件获取授权密钥,但无法调用其他API接口
  • 所有API在Postman中均可正常请求,但集成到React后完全失效
  • 调用费率和运输时间查询接口时触发CORS错误

相关代码

请求代码

let body = JSON.stringify({
  "accountNumber": {
    "value": "XXXXXXXXX"
  },
  "requestedShipment": {
    "shipper": {
      "address": {
        "postalCode": 75063,
        "countryCode": "US"
      }
    },
    "recipient": {
      "address": {
        "postalCode": "L0J 0A0",
        "countryCode": "CA"
      }
    },
    "pickupType": "DROPOFF_AT_FEDEX_LOCATION",
    "serviceType": "FEDEX_GROUND",
    "rateRequestType": [
      "LIST",
      "ACCOUNT"
    ],
    "customsClearanceDetail": {
      "dutiesPayment": {
        "paymentType": "SENDER",
        "payor": {
          "responsibleParty": null
        }
      },
      "commodities": [{
        "description": "Camera",
        "quantity": 1,
        "quantityUnits": "PCS",
        "weight": {
          "units": "KG",
          "value": 20
        },
        "customsValue": {
          "amount": 100,
          "currency": "USD"
        }
      }]
    },
    "requestedPackageLineItems": [{
      "weight": {
        "units": "KG",
        "value": 20
      }
    }]
  }
});
axios.post("https://apis-sandbox.fedex.com/rate/v1/rates/quotes", body, {
  headers : {
  "Accept": "*/*",
  "Content-Type": "application/json",
  "authorization": `Bearer XXX`,
  "Access-Control-Allow-Origin": "*",
}
}).then(res => console.log(res.data));

引入的依赖脚本

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

错误截图

CORS Error


解决方案

1. 移除无效请求头

请求头里的Access-Control-Allow-Origin: *是服务器返回给浏览器的响应头,不是前端请求需要携带的参数,浏览器会自动忽略该请求头,直接删除即可。

2. 开发环境配置代理绕过CORS

React开发环境可通过代理解决跨域问题:

  • 在项目根目录创建setupProxy.js文件,添加以下代码:
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/fedex-api',
    createProxyMiddleware({
      target: 'https://apis-sandbox.fedex.com',
      changeOrigin: true,
      pathRewrite: {
        '^/fedex-api': ''
      }
    })
  );
};
  • 修改请求URL为代理地址:
axios.post("/fedex-api/rate/v1/rates/quotes", body, {
  headers : {
    "Accept": "*/*",
    "Content-Type": "application/json",
    "authorization": `Bearer XXX`,
  }
})

3. 生产环境通过后端转发请求

生产环境不能依赖前端代理,必须通过自身后端服务器转发FedEx API请求:

  • 后端创建中转接口(如/api/fedex/rate),接收前端参数
  • 后端在中转接口内部调用FedEx官方API,将结果返回给前端
  • 前端直接请求自身后端的中转接口,规避跨域限制

4. 检查FedEx账号配置

确认FedEx开发者账号已将前端域名添加到允许访问的白名单中,部分API服务商对浏览器端请求有域名白名单限制,Postman不受此限制但浏览器会触发校验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:55:21