redux-api-middleware icon indicating copy to clipboard operation
redux-api-middleware copied to clipboard

201 response with empty body raise Error

Open afnecors opened this issue 8 years ago • 2 comments

This is my network response

schermata 2016-07-06 alle 15 54 11 1

But I get {name: "InternalError", message: "Unexpected end of JSON input"} I think because of JSON.parse(""). How can I fix it?

afnecors avatar Jul 06 '16 14:07 afnecors

Properly speaking, "" is not valid JSON, so it is the server's fault: it should not send a Content-Type: application/json header with such a body, even with Content-Length: 0 — it should send {} instead. That said, and knowing that we do not live in a perfect world, it should be almost trivial to accomodate this by changing this line.

My question is: are there any similar circumstances that we should take into account here?

agraboso avatar May 01 '17 20:05 agraboso

@afnecors What would you expect the payload to be? Does a custom payload method work? Something like:

  const anAction = {
    [CALL_API]: {
      endpoint: 'http://127.0.0.1/api/users',
      method: 'POST',
      body: JSON.stringify({}),
      headers: { 'Content-Type': 'application/json' },
      types: [
        'REQUEST',
        {
          type: 'SUCCESS',
           // Skip the payload, since it is known to be invalid JSON
          payload: (action, state, res) => ({}),
        },
        'FAILURE'
      ]
    }
  };

@agraboso some ways this could be handled are allowing emptyCodes to be configured in getJSON, or something like a looseParse flag. That way we don't have to worry about all the unknowns and users can opt-in to this behavior when they are working with odd APIs.

I do think the current behavior is valid, though. The resulting success action looks like:

{
  type: 'SUCCESS',
  payload: { <InternalError> Unexpected end of JSON input },
  error: true
}

I suggest we put a test around this case, and consider changing things if custom payloads don't cut it. How does that sound?

nason avatar May 17 '17 15:05 nason