Skip to content

cli

shell
# 安装edgeone cli
npm install -g edgeone

# 登录
edgeone login

# 在项目中初始化pages需要的环境
edgeone pages init

# 启动本地服务
edgeone pages dev

# 使用KV存储 
edgeone pages link

request

解析请求url

text
// 解析请求 URL
const url = new URL(request.url)
// 提取 URL 各个组成部分
const {
    href, // 完整 URL
    protocol, // 协议(如 http:)
    hostname, // 主机名(如 example.com)
    port, // 端口(如果有指定)
    pathname, // 路径(如 /path)
    search, // 查询字符串(如 ?query=123)
    hash // 井号后面的片段(如 #section)
} = url

proxy

  1. 创建 [[default]].js
  2. 添加以下代码
text
export async function onRequest({request, params, env}) {
    const requestUrl = request.url;
    const requestMethod = request.method;
    const proxyPath = requestUrl.substring(requestUrl.indexOf("/api/") + 4);
    request.headers.forEach((k,v)=>console.log(k,v))
    console.log(requestMethod,proxyPath, params, request.text())
    const res = await fetch("https://domain"+proxyPath, {
        method: 'POST',
        eo: {
            timeoutSetting: {
                connectTimeout: 60000,
                readTimeout: 60000,
                writeTimeout: 60000,
            },
        }
    });
    const resText = await res.text();
    return new Response(resText, {
        headers: {
            'content-type': 'application/json; charset=UTF-8',
            'Access-Control-Allow-Origin': '*',
        },
    });
}

访问信息

text
export async function onRequest({request, params, env}) {
    // my_kv 是您在项目中绑定命名空间时的变量名
    const visitCount = await kv.get('visitCount');
    let visitCountInt = Number(visitCount);
    visitCountInt += 1;
    await kv.put('visitCount', visitCountInt.toString());
    var eo = request.eo;
    const res = JSON.stringify({
        visitCount: visitCountInt,
        clientIp: eo.clientIp,
        countryName: eo.geo.countryName
    });
    return new Response(res, {
        headers: {
            'content-type': 'application/json; charset=UTF-8',
            'Access-Control-Allow-Origin': '*',
        },
    });
}

设置不缓存

text
{
  "caches": [
    {
      "source": "/*",
      "cacheTtl": 0
    }
  ],
  "headers": [
    {
      "source": "/*",
      "headers": [
        {
          "key": "Cache-Control",
          "value": "no-store, no-cache, must-revalidate, max-age=0"
        }
      ]
    }
  ]
}