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

Chrome中无法读取Cloudflare Worker POST接口响应体的问题

问题原因与解决方案

核心问题:mode: 'no-cors'限制了响应读取

你代码里设置的mode: 'no-cors'是导致无法读取响应体的直接原因。在这个模式下,浏览器会完全限制JavaScript访问响应的任何内容(包括状态码、响应头、响应体),返回的是一个不透明响应(opaque response),根本无法解析成JSON。

Postman能正常工作是因为它是后端请求工具,不受浏览器的CORS跨域政策约束,所以不需要考虑这个限制。

解决步骤

1. 移除前端代码中的mode: 'no-cors'

直接删除请求选项里的mode: 'no-cors',因为你需要读取响应内容,这个模式完全不适用。

2. 配置Cloudflare Worker的CORS规则

要让浏览器允许跨域请求,你的Cloudflare Worker必须返回正确的CORS响应头,同时处理OPTIONS预检请求(因为POST请求带Content-Type: application/json会触发浏览器的预检机制)。

在你的Cloudflare Worker代码中添加以下逻辑:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  // 处理OPTIONS预检请求
  if (request.method === 'OPTIONS') {
    return new Response(null, {
      headers: {
        'Access-Control-Allow-Origin': '你的前端域名', // 比如https://your-frontend.com,生产环境不建议用*允许所有
        'Access-Control-Allow-Methods': 'POST, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type',
      },
    });
  }

  // 处理POST请求的原有逻辑
  if (request.method === 'POST') {
    // 你的业务逻辑...
    const response = await fetch(/* 你的内部请求目标 */);
    // 添加CORS头到响应
    const modifiedResponse = new Response(response.body, response);
    modifiedResponse.headers.set('Access-Control-Allow-Origin', '你的前端域名');
    return modifiedResponse;
  }

  return new Response('Method not allowed', { status: 405 });
}

3. 调整前端请求代码(优化版)

移除mode: 'no-cors'后,添加响应状态检查,避免在请求失败时尝试解析JSON:

const url = `${process.env.SOME_URL}/v1/method?token=${TOKEN}`;
const headers = new Headers();
headers.append("Content-Type", "application/json;charset=UTF-8");

const requestOptions = {
    method: 'POST',
    redirect: 'follow',
    body: JSON.stringify(body),
    headers
};

return fetch(url, requestOptions)
    .then(async (response) => {
        // 先检查响应状态是否正常
        if (!response.ok) {
            throw new Error(`请求失败,状态码:${response.status}`);
        }
        return response.json();
    })
    .then(result => console.log(result))
    .catch(error => console.log('error', error));

补充说明

  • 如果你的前端和Worker在同一域名下(比如Worker作为子域名服务),可能不需要配置CORS,但大多数跨域场景下必须添加上述头。
  • 生产环境中不要用Access-Control-Allow-Origin: *,指定具体的前端域名更安全。

内容的提问来源于stack exchange,提问作者Bogdan M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:03:31