Cloudflare Worker Error: Steaming vs Buffer Response

#1

Hi team

I’m playing around with Cloudflare workers and have hit the following error when trying to proxy a POST request (to a Wordpress blog):

TypeError: A request with a one-time-use body (it was initialized from a stream, not a buffer) encountered a redirect requiring the body to be retransmitted. To avoid this error in the future, construct this request from a buffer-like body initializer.

I tried the advice in this post (with reference to Requests, but I guessed it was the same) with no joy - even if I created a new response, the problem remained.

Can anybody advise on the best way to structure the response so that the redirect doesn’t cause an issue? Or is there a bigger problem with my code that I’m not seeing?

Full code below…

Thanks,

Nicholas

addEventListener('fetch', event => {

  var url = new URL(event.request.url);

  if (url.pathname.startsWith('/blog') || url.pathname === '/blog') {
    if (reqType === 'POST') {
      event.respondWith(handleBlogPost(event, url));
    } else {
      handleBlog(event, url);
    }
  } else {
   event.respondWith(fetch(event.request));
  }
})

async function handleBlog(event, url) {
  var newBlog = "https://foo.com";
  var originUrl = url.toString().replace(
    'https://www.bar.com/blog', newBlog);
  event.respondWith(fetch(originUrl)); 
}

async function handleBlogPost(event, url) {
  try {
    var newBlog = "https://foo.com";
    var srcUrl = "https://www.bar.com/blog";

    const init = {
      method: 'POST',
      headers: event.request.headers,
      body: event.request.body
    };
    var originUrl = url.toString().replace( srcUrl, newBlog );

    const response = await fetch(originUrl, init)

    return new Response(response.body, { headers: response.headers })

  } catch (err) {
    // Display the error stack.
    return new Response(err.stack || err)
  }
}
#3

For anybody else who comes across this problem, I got an amazing answer on SO: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body

Fixed by passing the whole request (event.request) in instead of the init block I’d constructed.

2 Likes
#4

Thanks for sharing the solution

1 Like