使用memos API 通过 CF workers中转获取json

浪子
2024-05-21 / 1 评论 / 搜一下 / 160 阅读 / 正在检测是否收录...
AI摘要:本文介绍了如何使用memos API通过CF workers中转获取json数据。首先,需要新建一个workers,并粘贴提供的代码。然后,将代码中的`https://memos.ee`和`your_real_token_here`分别替换为自己的memos地址和access token。如果不是uid为1的用户,还可以修改`users/1`的值为自己的uid。最后,通过访问https://bbapi.memos.ee进行演示。

新建一个workers

粘贴以下代码

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

async function handleRequest(request) {
  const baseUrl = 'https://memos.ee'; // 假设这是API的基础URL
  
  try {
    // 创建URL对象,包含API的路径
    const url = new URL(`${baseUrl}/api/v1/memos`);

    // 创建查询参数对象
    // 假设我们要添加参数 'creator' 与 'visibility'
    // 转义已经完成不需要额外转义 'visibilities == ['PUBLIC'] && creator == 'users/1''
    const params = new URLSearchParams({
      filter: "visibilities == ['PUBLIC'] && creator == 'users/1'",
      pageSize: "200"
    });

    // 将查询参数对象与URL对象结合
    url.search = params.toString();

    // 发起GET请求到带有查询参数的URL
    const response = await fetch(url.toString(), { // Make sure to call toString()
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        // 如果API需要认证,在这里添加'Authorization'头
        'Authorization': 'Bearer your_real_token_here' // 替换为实际的token
      }
    });

    // 检查响应状态
    if (!response.ok) {
      throw new Error(`Network response was not ok: ${response.status}`);
    }

    // 读取响应主体(假设返回JSON数据)
    const data = await response.json();
    
    // 返回获取到的数据
    return new Response(JSON.stringify(data), {
      headers: { 'content-type': 'application/json' }
    });

  } catch (error) {
    // 错误处理,返回错误详情
    return new Response(JSON.stringify({ error: error.message }), {
      status: 500, // 返回服务端错误状态码
      headers: { 'content-type': 'application/json' }
    });
  }
}

修改其中的https://memos.eeyour_real_token_here为自己的memos地址access token .
如果不是uid为1的用户可以修改users/1的值为自己的uid.

即可

演示 https://bbapi.memos.ee

评论 (1)

取消
  1. 头像

    [...]AI摘要:使用memos API构建了一个朋友圈的页面,页面样式来自于typecho主题`icefox`。可以通过演示地址https://m.memos.ee查看页面效果。 样式来自于typecho主题 icefoxAPI 通过https://blog.memos.ee/archives/207.html 获取演示地址 https://m.memos.ee[...]

    回复