FETCH POST Type Error Failed to execute function

Multiple people have brought up issues similar to mine in this community and stack overflow. It still seems largely unsolved so I’m asking in hopes of a solution.

I’m trying to create a feature for users to sign up through mailchimp. User info goes from browser to workers to mail chimp. I’m getting the following errors:

  1. TypeError: Failed to execute function: parameter 1 is not of type ‘Response’. at line 0, col -2
  2. Request.Body is not being read

Request from Client:

        const response = await axios({
          method: "post",
          url: "http://127.0.0.1:8787/signup",
          data: {
            MERGE0: email,
            MERGE1: firstName,
            MERGE2: lastName,
          },
          headers: {
              "content-type": "application/json",
          }
        });

Workers part 1 (function to read request body):
https://developers.cloudflare.com/workers/examples/read-post

async function readRequestBody(request) {
  const { headers } = request
  const contentType = headers.get('content-type') || ''

  if (contentType.includes('application/json')) {
    return JSON.stringify(await request.json())
  } else if (contentType.includes('application/text')) {
    return request.text()
  } else if (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 JSON.stringify(body)
  } else {
    // Perhaps some other type of data was submitted in the form
    // like an image, or some other binary data.
    return 'a file'
  }
}

Workers part 2 (to Post JSON File to Mail Chimp):
https://developers.cloudflare.com/workers/examples/post-json

async function gatherResponse(response) {
  const { headers } = response
  const contentType = headers.get('content-type') || ''
  if (contentType.includes('application/json')) {
    return JSON.stringify(await response.json())
  } else if (contentType.includes('application/text')) {
    return response.text()
  } else if (contentType.includes('text/html')) {
    return response.text()
  } else {
    return response.text()
  }
}

Workers Part 3 (to Handle Post Request):

async function eventHandler(request) {
  const pathname = request.url

  try {
    if (pathname.indexOf('signup') !== -1) {
      const reqBody = await readRequestBody(request)
      const { MERGE0, MERGE1, MERGE2 } = reqBody

      // Construct req data
      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}`,
        },
        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)
      return results
    }
  } catch (err) {
    console.log(err)
  }
}

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

A few other posts I’ve referenced:

So, your eventHandler needs to return a Response or a Promise<Response>. Right now you’re returning a string.

Your gatheresponse will always return Response#text() or JSON.stringify(Response#json()) - both of these return a string. You just need to wrap that results variable in a Response with return new Response(results)
Your catch is also not returning anything. I recommend returning a 500 here. new Response(null, { status: 500 })

Thanks, that seemed to remove the TypeError.

I’m still having an issue with Request.Body not being able to be read.

When I console.log MERGE0, MERGE1, and MERGE2, it comes out as undefined. The readRequestBody function returns ‘a file’.

So as it turns out, my workers couldn’t read request.body because it was blocked by the CORS.

I used this to overcome it: https://developers.cloudflare.com/workers/examples/cors-header-proxy

Once I got it to work, I found out I didn’t need the gatherResponse function anymore.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.