Search code examples
node.jsreact-nativefetchresponseresponse-headers

How to access response headers in React Native


I am having troubles with some requests I am making from my React Native app, to my NodeJS server.

One of the endpoints being called, can return a 409 error for one of two reasons, therefore I need to access the message that was thrown along with this error.

I can see the message in the Response Headers in Chrome's Dev Tools, but I am struggling to access it.

  await fetch(
    new Request(`${Constants?.manifest?.extra?.hostname}/ext/external-users`, {
      method: 'POST',
    }),
    {
      body: formData,
      headers,
    }
  ).then(async response => {
    if (response.status == 200) {
      await response.json().then(({ externalUser, token }) => {
        result.createdUser = externalUser
        result.tabledAuthToken = token
      })
    } else if (response.status == 409) {
      const errorMessage = response.headers.get('x-exit')
      if (errorMessage?.toLowerCase() === ERROR_MESSAGES.INVALID_VERSION) {
        throw new Error(ERROR_MESSAGES.INVALID_VERSION)
      }
      throw Error(`There was a problem when trying to log in user: ${emailAddress}. Please, try again later.`)
    }
  })

When I log the output of errorMessage, it is just null. I have seen people say to use .json().then(...), but this fails because response is not a JSON.


Solution

  • I managed to resolve this issue, the problem was in our backend server. Me and a co-worker worked in parallel on a feature. In the backend, he forgot to add allowResponseHeaders: 'x-exit' to our security file. Once this was added, I was able to get the error message from the response headers.