0

I wrote a cloudflare worker to check headers for authorization. If it is missing, just forward the requests. I found most requests are ok, but some post requests throws errors like this:

  "exceptions": [
    {
      "name": "TypeError",
      "message": "Cannot reconstruct a Request with a used body.",
      "timestamp": 1688611154771
    }
  ],
  "logs": [
   {
      "message": [
      "forwarded: https://..."
       ],
      "level": "log",
      "timestamp": 1688611154771
   }
 ]

And the code throws exception is like this:

export default {
  async fetch(request, env, ctx) {
    // let error pass to the origin server
    ctx.passThroughOnException();

    let fwd_request = new Request(request);
    const headers = request.headers;
    const auth = headers.get('Authorization')
    if (!auth) {       
     console.log(`forwarded: ${request.url}`)
     return fetch(request);
    }
    ...

So, the console.log is printed out, and fetch(request) doesn't change the original request.

Why I am getting this error?

reachlin
  • 4,516
  • 7
  • 18
  • 23

1 Answers1

1

This line:

let fwd_request = new Request(request);

consumes the original request's body, and transfers it to fwd_request. If you try to do fetch(request) after this, and it has a body, it won't work. You could do fetch(fwd_request) instead, or you could delay constructing fwd_request until after the if (!auth) block, since it looks like you don't use it before that block anyway.

export default {
  async fetch(request, env, ctx) {
    // let error pass to the origin server
    ctx.passThroughOnException();

    const headers = request.headers;
    const auth = headers.get('Authorization')
    if (!auth) {       
     console.log(`forwarded: ${request.url}`)
     return fetch(request);
    }
    let fwd_request = new Request(request);
    ...
Kenton Varda
  • 41,353
  • 8
  • 121
  • 105