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

React通过Axios调用AWS Serverless API时出现CORS错误

解决React前端调用Serverless API的CORS错误(数据已写入但报错)

数据能成功写入DynamoDB,说明业务逻辑没问题,CORS错误的核心原因是API返回的响应缺少跨域允许的HTTP头,同时API Gateway的预检请求(OPTIONS)可能未正确配置。以下是具体解决步骤:

1. 修改Lambda代码,添加跨域响应头

在Lambda返回的响应中,必须包含Access-Control-Allow-Origin等CORS相关头,不管请求成功还是失败都要加:

const createRecord = async (event) => {
    const response = { 
        statusCode: 200,
        // 添加CORS响应头
        headers: {
            "Access-Control-Allow-Origin": "*", // 生产环境请替换为你的前端域名,比如"https://your-app.com"
            "Access-Control-Allow-Headers": "Content-Type",
            "Access-Control-Allow-Methods": "POST, OPTIONS"
        }
    };

    try {
        const body = JSON.parse(event.body);
        const params = {
            TableName: process.env.DYNAMODB_TABLE_NAME,
            Item: marshall(body || {}),
        };
        const createResult = await db.send(new PutItemCommand(params));
        response.body = JSON.stringify({
            message: "Successfully created record.",
            createResult,
        });
    } catch (e) {
        console.error(e);
        response.statusCode = 500;
        response.body = JSON.stringify({
            message: "Failed to create record.",
            errorMsg: e.message,
            errorStack: e.stack,
        });
    }

    return response;
};

注意:生产环境不要用*,指定具体域名能避免安全风险。

2. 配置API Gateway的CORS并部署

API Gateway需要正确处理浏览器发送的OPTIONS预检请求,步骤如下:

  • 登录AWS控制台,打开API Gateway服务,找到你的目标API
  • 选中POST接口所在的资源,点击顶部「Actions」→「Enable CORS」
  • 在弹窗中填写:
    • Access-Control-Allow-Origin:和Lambda里的域名一致(或*用于测试)
    • Access-Control-Allow-Headers:Content-Type
    • Access-Control-Allow-Methods:POST, OPTIONS
  • 点击「Enable CORS and replace existing CORS headers」,然后点击「Deploy API」(必须部署才会生效)

3. 调整前端Axios请求的Content-Type(可选但更规范)

你当前设置Content-Type: text/plain,但Lambda里用JSON.parse解析请求体,建议改成application/json更符合REST规范,避免潜在的解析问题:

import axios from "axios";

export const sendItemToDB = async (_data) => {
    if (!_data) { return };
    try {
        const res = await axios({
            method: "POST",
            url: process.env.REACT_APP_QUERY_API,
            data: _data,
            headers: {
                "Content-Type": "application/json" // 修改这里
            },
        });
        console.log("data returned from api", res);
    } catch (error) {
        console.log("Error sending File to db: ");
        console.log(error);
    }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:15:35