Cloudflare Workers POST请求TypeError及RequestBody无法读取问题求助
问题根因
parameter 1 is not of type 'Response'报错:Cloudflare Workers的event.respondWith()方法要求必须返回标准Response实例,你当前代码直接返回接口响应字符串、路径不匹配时返回undefined、异常捕获后无返回值,均不符合接口要求。- 请求体读取失败报错:你的
readRequestBody函数处理JSON请求时,将解析后的JSON对象又转成了字符串返回,后续直接对字符串做解构取值,必然得到undefined,相当于未成功读取请求参数。 - 隐藏问题:向Mailchimp接口发POST请求时未携带
Content-Type: application/json请求头,Mailchimp会无法识别请求体格式,导致请求失败。
修复方案
1. 修正请求体读取函数
调整readRequestBody逻辑,JSON/表单类型直接返回对象,不要额外转字符串:
async function readRequestBody(request) { const { headers } = request const contentType = headers.get('content-type') || '' if (contentType.includes('application/json')) { // 直接返回解析后的JSON对象 return await request.json() } else if (contentType.includes('application/text') || contentType.includes('text/html')) { return request.text() } else if (contentType.includes('form')) { const formData = await request.formData() const body = {} for (const entry of formData.entries()) { body[entry[0]] = entry[1] } return body } else { return 'a file' } }
2. 修正主逻辑,统一返回Response实例
所有分支都返回标准Response对象,补充Mailchimp请求的必要头,补全边界场景处理:
async function eventHandler(request) { // 用URL类解析路径更可靠,避免域名等字符干扰 const pathname = new URL(request.url).pathname const responseHeaders = { "Access-Control-Allow-Origin": "*", // 按需调整跨域规则 "Content-Type": "application/json" } try { if (pathname === '/signup') { const reqBody = await readRequestBody(request) const { MERGE0, MERGE1, MERGE2 } = reqBody const data = { members: [ { email_address: MERGE0, status: 'subscribed', merge_fields: { FNAME: MERGE1, LNAME: MERGE2, }, }, ], } const postData = JSON.stringify(data) const options = { method: 'POST', headers: { Authorization: `auth ${MAILCHIMP_API_KEY}`, // 补充Mailchimp要求的JSON请求头 "Content-Type": "application/json", }, body: postData, } const url = `https://us5.api.mailchimp.com/3.0/lists/${MAILCHIMP_AUDIENCE_ID}` const res = await fetch(url, options) const results = await gatherResponse(res) // 包裹为Response对象返回 return new Response(results, { headers: responseHeaders, status: res.status }) } // 路径不匹配场景返回 return new Response(JSON.stringify({msg: "接口不存在"}), { headers: responseHeaders, status: 404 }) } catch (err) { console.log(err) // 异常场景返回错误响应 return new Response(JSON.stringify({msg: "服务异常", error: err.message}), { headers: responseHeaders, status: 500 }) } }
可选优化
如果前端存在跨域预检请求,需要额外添加OPTIONS请求的处理逻辑,返回正确的跨域允许头即可。
内容的提问来源于stack exchange,提问作者Warner Lin
相关产品推荐
相关产品推荐

