3

I have 2 apps on vercel - one is nextjs, the other is FastAPI in python. The nextjs node api needs to get some data from the FastApi app. I keep getting this content-header mismatch. What am I missing?

cause: RequestContentLengthMismatchError: Request body length does not match content-length header
      at AsyncWriter.end (node:internal/deps/undici/undici:8417:19)
      at writeIterable (node:internal/deps/undici/undici:8327:16) {
    code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
  }

My post request in node API:

const body = JSON.stringify({ data: value })
  const response = await fetch(`${FAST_API_HOST}/api/data`, {
    method: 'POST',
    headers: {
      'Accept': 'application/json; charset=utf-8',
      'Content-Type': 'application/json',
      'Content-Length': body.length.toString(),
      'Connect': 'keep-alive',
    },
    body
  })
    .then(async res => {
      if (res.status === 200) return res.json();
      else throw new Error(await res.text())
    })
hammies
  • 1,344
  • 2
  • 22
  • 46
  • Have a look at related answers [here](https://stackoverflow.com/a/73761724/17865804) and [here](https://stackoverflow.com/a/70636163/17865804) as well. – Chris Feb 17 '23 at 06:14
  • @Chris not sure what I’m suppose to look at at those links. I want to mention this all works in local environment but calling node (local and prod) to fastapi (prod) doesn’t work. – hammies Feb 17 '23 at 08:16
  • @Chris sorry, node local to fastapi prod also works. So prod to prod doesn’t work. – hammies Feb 17 '23 at 08:24
  • @Chris I've already tried that first. It was because of the error, I added that. – hammies Feb 17 '23 at 12:32
  • According to the [Node documentation](https://nodejs.org/api/http.html#class-httpclientrequest), ‘`Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes.’ So you should replace `body.length.toString()` by `Buffer.byteLength(body)`. But if your JSON only has ASCII characters it will be equal to `body.length` so not sure this is the cause of your issue. It seems like a bug in Undici. – Géry Ogam Mar 22 '23 at 19:35

0 Answers0