Skip to content

Missing CORS when bodyParser throws an error #365

Open
@richardgarnier

Description

@richardgarnier

Here's my config:

settings: {
    log4XXResponses: false,
    logRouteRegistration: 'debug',
    port: 8081,

    cors: {
      origin: '**',
      credentials: true,
      exposedHeaders: ['Content-Type', 'Content-Disposition'],
    },

    routes: [
      {
        path: '/',
        name: 'default',
        authentication: true,
        authorization: true,
        autoAliases: true,
        logging: true,

        bodyParsers: {
          json: true,
          urlencoded: { extended: true },
        },
      },
    ],
  },

When I call the endpoint and I get for example a validation error, I get something like this, which is expected. Note that this is slightly edited for brevity.

[8:48] ~  > curl 'http://localhost:8081/test' -X POST -H 'content-type: application/json' -H 'Origin: http://localhost:8083' --data-raw '{"i": 1}' -v
> POST /test HTTP/1.1
> Host: localhost:8081
> User-Agent: curl/8.6.0
> Accept: */*
> content-type: application/json
> Origin: http://localhost:8083
> Content-Length: 8
>
< HTTP/1.1 422 Unprocessable Entity
< X-Request-ID: dc455b2a-114c-45ff-b40d-036f9685465b
< Access-Control-Allow-Origin: http://localhost:8083
< Vary: Origin
< Access-Control-Allow-Credentials: true
< Access-Control-Expose-Headers: Content-Type, Content-Disposition
< Access-Control-Allow-Methods: GET, HEAD, PUT, PATCH, POST, DELETE
< Content-type: application/json; charset=utf-8
< Date: Mon, 26 May 2025 06:49:17 GMT
< Connection: keep-alive
< Keep-Alive: timeout=5
< Transfer-Encoding: chunked
<
{"name":"ValidationError","message":"X","code":422,"type":"XXX","data":[...]}

However, when I call the endpoint with an invalid body, the CORS Headers are missing:

[8:42] ~  > curl 'http://localhost:8081/test' -X POST -H 'content-type: application/json' -H 'Origin: http://localhost:8083' --data-raw null -v
> POST /test HTTP/1.1
> Host: localhost:8081
> User-Agent: curl/8.6.0
> Accept: */*
> content-type: application/json
> Origin: http://localhost:8083
> Content-Length: 4
>
< HTTP/1.1 400 Bad Request
< X-Request-ID: 7a592025-f142-4689-b0ef-d41476aad3a6
< Content-type: application/json; charset=utf-8
< Date: Mon, 26 May 2025 06:48:15 GMT
< Connection: keep-alive
< Keep-Alive: timeout=5
< Transfer-Encoding: chunked
<
{"name":"MoleculerError","message":"Unexpected token 'n', \"null\" is not valid JSON","code":400,"type":"entity.parse.failed"}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions