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

调用含访问码的API发起POST请求时遭遇CORS错误求解决方案

表单POST请求的CORS及API调用问题解决

原提交代码

bookingForm.addEventListener("submit", async (e) => {
    e.preventDefault();
    const {
        name,
        email,
        comments
    } = bookingForm.elements;
    const formData = {
        firstname: name.value,
        email: email.value,
        message: comments.value
    };
    console.log(formData);
    const response = await fetch(
        "https://forms.maakeetoo.com/formapi",
        {
            method: "POST",
            body: JSON.stringify(formData),
            headers: {
                "Content-type": "application/json; charset=UTF-8"
            }
        }
    );
    const json = await response.json();
    console.log(json);
});

触发的错误

Access to fetch at 'https://forms.maakeetoo.com/formapi' from origin 'http://15.206.68.78:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

错误位置:代码第79行const response = await fetch

核心问题梳理

  • API地址错误:实际应调用的地址是https://forms.maakeetoo.com/formapi/32,原代码使用了错误的端点
  • 缺少访问认证:API要求请求头携带Code字段(访问码),原请求未添加该认证信息
  • CORS跨域限制:当前请求源http://15.206.68.78:8081未被API服务器的跨域策略允许,导致预请求(OPTIONS)被拦截

分步解决方案

1. 修正API地址并添加访问码

将请求地址改为正确的端点,同时在请求头中加入Code字段(替换<你的实际访问码>为真实值),并添加异常捕获:

bookingForm.addEventListener("submit", async (e) => {
    e.preventDefault();
    const {
        name,
        email,
        comments
    } = bookingForm.elements;
    const formData = {
        firstname: name.value,
        email: email.value,
        message: comments.value
    };
    console.log(formData);
    try {
        const response = await fetch(
            "https://forms.maakeetoo.com/formapi/32", // 修正后的API地址
            {
                method: "POST",
                body: JSON.stringify(formData),
                headers: {
                    "Content-type": "application/json; charset=UTF-8",
                    "Code": "<你的实际访问码>" // 添加API要求的访问码
                }
            }
        );
        const json = await response.json();
        console.log(json);
    } catch (error) {
        console.error("请求失败:", error);
    }
});

2. 解决CORS跨域问题

CORS错误的根源是API服务器未配置允许你的请求源,有两种可行处理方式:

  • 正规解决(推荐):联系API服务提供者,将http://15.206.68.78:8081添加到服务器的Access-Control-Allow-Origin允许列表中,这是符合跨域规范的长期解决方案
  • 开发测试临时绕过:如果仅用于本地开发测试,可以使用浏览器CORS插件,或者搭建本地代理服务器转发请求,避免直接跨域调用。注意:不要使用no-cors模式,该模式会导致无法读取响应内容,无法验证请求是否成功

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:05:14