kwhitley / itty-router

A little router.
MIT License
1.69k stars 77 forks source link

`withContent` returns a 500 when no body is sent #216

Closed smcstewart closed 3 months ago

smcstewart commented 5 months ago

Describe the Issue

When no body is sent with a request that uses the withContent middleware, a 500 Internal Server Error is returned. The expectation is possibly for a 400 Bad Request instead, since you were expecting a body, but didn't receive one - hence bad input.

Example Router Code

Please provide the itty-router code related to the issue. If possible, create a minimal, reproducible example.

import { Router, error, json, withContent } from 'itty-router';

const router = Router();

router
    .post('/', withContent, ({ content }) => console.log(content))

    .all('*', () => error(404));

export default {
    fetch: async (request, env, ctx) =>
        router.handle(request, env, ctx).then(json).catch(error)
};

Request Details

Steps to Reproduce

Steps to reproduce the behaviour:

  1. Install and run dev server (uses npm below, but use whatever package manager you like):
git clone git@github.com:smcstewart/itty-router-without-content.git
cd itty-router-without-content
npm install
npm run dev
  1. Open a new terminal and run cURL (or whatever else you like: e.g. httpie) and perhaps something like jq for a pretty-printed response:
curl -v --request POST \
  --url http://localhost:8787/ \
  --header 'Content-Type: application/json'
  1. You will see a HTTP 500 Internal Server Error and the following JSON response:
{
  "status": 500,
  "error": "Unexpected end of JSON input"
}

Expected Behaviour

I would expect to see a 400 Bad Request since the input is bad.

Actual Behaviour

It currently returns a 500 Internal Server Error.

Environment (please complete the following information):

Additional Context

None.

kwhitley commented 3 months ago

Closed thanks to your PR :)