← 返回
未分类

edgeone-CORS跨域

解决 EdgeOne Pages 跨域请求问题的完整方案。 当用户提到以下关键词时触发: - "edgeone 跨域" - "EdgeOne CORS" - "跨域请求失败" - "CORS error edgeone" - "百度 API 跨域" - "aip.baidubce 跨域" - "第三方接口 跨域"
解决 EdgeOne Pages 跨域请求问题的完整方案。 当用户提到以下关键词时触发: - "edgeone 跨域" - "EdgeOne CORS" - "跨域请求失败" - "CORS error edgeone" - "百度 API 跨域" - "aip.baidubce 跨域" - "第三方接口 跨域"
彭延伟
未分类 community v1.0.1 2 版本 98989.9 Key: 无需
★ 0
Stars
📥 98
下载
💾 2
安装
2
版本
#latest

概述

EdgeOne CORS 跨域解决方案

问题背景

EdgeOne Pages 托管的静态页面直接请求第三方 API(如百度 AI)时,会遇到浏览器跨域限制(CORS Error)。解决方案是通过 Edge Function 作为代理中转请求。

架构图

浏览器 → EdgeOne 静态页面 → Edge Function (代理) → 第三方 API
                                  ↓
                            添加 CORS 头

快速修复模板

1. 创建 Edge Function 代理

在项目根目录创建以下结构:

your-project/
├── index.html
└── edge-functions/
    └── api/
        └── [your-api-name].js    ← 代理函数

2. Edge Function 代码模板

// edge-functions/api/[your-api-name].js
// 代理请求第三方 API 并添加 CORS 头
// ⚠️ 重要:敏感凭证不要硬编码,使用环境变量

export default async function onRequest(context) {
  // 1. 配置你的第三方 API
  const TARGET_API = 'https://api.example.com';
  
  // 2. 获取凭证(优先使用环境变量)
  const apiKey = context.env.API_KEY || 'YOUR_API_KEY';  // ← 使用环境变量
  
  // 3. 从请求中获取参数
  const url = new URL(context.request.url);
  const param1 = url.searchParams.get('param1');
  
  try {
    // 4. 发起请求到目标 API
    const response = await fetch(`${TARGET_API}?key=${apiKey}&param1=${param1}`, {
      method: 'GET', // 或 POST
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
      // POST 请求 body:
      // body: JSON.stringify({ key: 'value' })
    });
    
    const data = await response.json();
    
    // 5. 返回带 CORS 头的响应
    return new Response(JSON.stringify(data), {
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',      // 允许所有来源
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization'
      },
      status: response.ok ? 200 : response.status
    });
    
  } catch (error) {
    return new Response(JSON.stringify({
      error: '代理请求失败',
      message: error.message
    }), {
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      status: 500
    });
  }
}

凭证配置方式

⚠️ 安全警告

不要将敏感凭证(如 client_secret、API Key)硬编码在代码中!

推荐方式:环境变量

在 EdgeOne 控制台设置环境变量:

CLIENT_ID = your_client_id
CLIENT_SECRET = your_client_secret

Edge Function 中通过 context.env 读取:

const clientId = context.env.CLIENT_ID;
const clientSecret = context.env.CLIENT_SECRET;

备选方式:配置文件

在 Edge Function 中使用本地配置文件(仅供本地测试):

// ⚠️ 仅供本地测试,生产环境请使用环境变量
const CONFIG = {
  client_id: 'YOUR_CLIENT_ID',
  client_secret: 'YOUR_CLIENT_SECRET'
};

// 检查是否配置
if (!clientId || clientId === 'YOUR_CLIENT_ID') {
  return new Response(JSON.stringify({
    error: '请先配置凭证'
  }), { status: 400 });
}

完整 Demo 示例

参考 demo/ 目录中的完整示例:

文件说明
------------
demo/index.html前端页面,调用代理 API
demo/edge-functions/api/token.jsEdge Function 代理(含凭证配置示例)

Demo 效果

  • 前端请求 /api/token
  • Edge Function 代理请求百度 OAuth API
  • 返回带 CORS 头的响应
  • 前端成功获取 Access Token

配置 Demo 凭证

修改 demo/edge-functions/api/token.js 中的 CONFIG:

const CONFIG = {
  client_id: '你的_client_id',           // ← 修改这里
  client_secret: '你的_client_secret'    // ← 修改这里
};

本地测试

cd demo
edgeone pages dev

然后访问本地预览地址测试。

部署到 EdgeOne

edgeone pages deploy demo -n your-project-name -t YOUR_API_TOKEN

常见第三方 API 代理示例

百度 AI Access Token(已配置凭证检查)

export default async function onRequest(context) {
  // 优先使用环境变量
  const clientId = context.env.CLIENT_ID || CONFIG.client_id;
  const clientSecret = context.env.CLIENT_SECRET || CONFIG.client_secret;
  
  // 检查凭证
  if (!clientId || !clientSecret) {
    return new Response(JSON.stringify({ error: '请配置凭证' }), { status: 400 });
  }
  
  const url = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}`;
  
  try {
    const response = await fetch(url, { method: 'POST' });
    const data = await response.json();
    
    return new Response(JSON.stringify(data), {
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      }
    });
  } catch (error) {
    return new Response(JSON.stringify({ error: error.message }), {
      status: 500,
      headers: { 'Access-Control-Allow-Origin': '*' }
    });
  }
}

POST 请求示例

export default async function onRequest(context) {
  const { request } = context;
  const body = await request.json();
  
  const response = await fetch('https://api.example.com/endpoint', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body)
  });
  
  const data = await response.json();
  
  return new Response(JSON.stringify(data), {
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type'
    }
  });
}

注意事项

  1. 环境变量优先:生产环境务必使用 EdgeOne 控制台设置环境变量
  2. 凭证检查:添加凭证是否配置的检查,避免未配置时直接请求
  3. 敏感信息:永远不要在前端暴露 client_secret
  4. CORS 头:始终返回正确的 CORS 头,包括错误情况
  5. 安全建议:生产环境建议将 Access-Control-Allow-Origin 设为具体域名

一键部署命令

edgeone pages deploy <项目目录> -n <项目名> -t <API_TOKEN>

每次更新代码后重新部署即可生效。

版本历史

共 1 个版本

  • v1.0.1 Initial release 当前
    2026-04-21 15:56 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

developer-tools

Github

steipete
使用 `gh` CLI 与 GitHub 交互,通过 `gh issue`、`gh pr`、`gh run` 和 `gh api` 管理议题、PR、CI 运行及高级查询。
★ 668 📥 324,211
security-compliance

Skill Vetter

spclaudehome
AI智能体技能安全预审工具。安装ClawdHub、GitHub等来源技能前,检查风险信号、权限范围及可疑模式。
★ 1,215 📥 266,574
ai-intelligence

ontology

oswalpalash
类型化知识图谱,用于结构化智能体记忆与可组合技能。支持创建/查询实体(人员、项目、任务、事件、文档)及关联...
★ 712 📥 243,883