我是 JavaScript 的新手,我正在尝试在 Cloudflare Worker 上使用 JS 为 IFTTT 创建一个 Github API 网关(因为它无法修改标头)。这是代码:async function handleRequest(request) { var url = new URL(request.url) var apiUrl = 'https://api.github.com' + url.pathname var basicHeaders = { 'User-Agent': 'cloudflare', 'Accept': 'application/vnd.github.v3+json' } const { headers } = request const contentType = headers.get('content-type') const contentTypeUsed = !(!contentType) if (request.method == 'POST' && contentTypeUsed) { if (contentType.includes('application/json')) { var body = await request.json() if ('additionHeaders' in body) { var additionHeaders = body.additionHeaders delete body.additionHeaders } var apiRequest = { 'headers': JSON.stringify(Object.assign(basicHeaders,additionHeaders)), 'body': JSON.stringify(body), } } else { return new Response('Error: Content-Type must be json', {status: 403}) } const newRequest = new Request(apiUrl, new Request(request, apiRequest)) try { var response = await fetch(newRequest) return response } catch (e) { return new Response(JSON.stringify({error: e.message}), {status: 500}) } } else { var apiRequest = { 'headers': JSON.stringify(basicHeaders) } const newRequest = new Request(apiUrl, new Request(request, apiRequest)) var response = await fetch(newRequest) return response }}addEventListener('fetch', async (event) => { event.respondWith(handleRequest(event.request))})
1 回答
茅侃侃
TA贡献1842条经验 获得超21个赞
修复这个:
let apiRequest = new Object
apiRequest.headers = Object.assign(basicHeaders, additionHeaders)
apiRequest.body = JSON.stringify(body)
意志apiRequest看起来像这样:
{headers:{},body:"{}"}
这似乎是RequestInitializerDict想要的。
添加回答
举报
0/150
提交
取消