TypeError:“RequestInitializerDict”上“headers”字段的类型不

我是 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))

})



POPMUISE
浏览 73回答 1
1回答

茅侃侃

修复这个:let apiRequest = new ObjectapiRequest.headers = Object.assign(basicHeaders, additionHeaders)apiRequest.body = JSON.stringify(body)意志apiRequest看起来像这样:{headers:{},body:"{}"}这似乎是RequestInitializerDict想要的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript