robinnnnn
robinnnnn

Reputation: 1735

Cannot access error response body from client when using nginx + lua

I'm using the following lua script to forward all server responses that are served from Node. My error handling for a /signup route works as follows:

if authenticationResult.status ~= 201 then
    ...

    ngx.status = authenticationResult.status
    ngx.say(authenticationResult.body)
    ngx.exit(401)
    return
end

From the client I send a typical signup request like so, using the superagent-promise library:

request
  .post(url)
  .type('form')
  .send(data)
  .end()
  .then((response) => {
    console.log('the response', response)
  })
  .catch((error) => {
    console.log('the error', error)
  })

When I send a valid post request from the client, the response variable in the .then successfully contains the response body.

However, when I sent an improper post request with invalid credentials, neither the .then nor the .catch executes. Instead, the Chrome console immediately displays POST http://api.dockerhost/signup 401 (Unauthorized).

I would like to know what I can do differently to successfully access the server's error response and its contents, outside of just its status code.

Upvotes: 0

Views: 978

Answers (1)

Adam B
Adam B

Reputation: 3833

Per the manual, you need to use ngx.HTTP_OK as the return if you want nginx to return content as part of the page. Otherwise it will simply return a 401.

ngx.status = authenticationResult.status
ngx.say(authenticationResult.body)
ngx.exit(ngx.HTTP_OK)
return

Upvotes: 1

Related Questions