How to get response status code


#1

I would like to know the status code of a response through a middleware. I tried response.status() without the parameter, but it does not return the current status code.


#2

The job of response.status is not set the response status and not to get it. Also please explain what you are trying to do and what code you have got so far


#3

I made a middleware to show in the console the accesses in the following model:

2018-10-15T20:29:18.321Z - info: ......127.0.0.1 > [...GET] example.com.br/api/v1/carrinho

My code so far is:

  async handle ({ request }, next) {
    let ip = request.ip()
    let method = request.method()

    if (ip.length < 15) {
      let spaces = 15 - ip.length
      for (let i = 0; i < spaces; i++) {
        ip = `.${ip}`
      }
    }

    if (method.length < 6) {
      let spaces = 6 - method.length
      for (let i = 0; i < spaces; i++) {
        method = `.${method}`
      }
    }

    Logger.info(
      `${ip} > [${method}] ${request.header('Host')}${request.originalUrl()}`
    )

    await next()
  }

It works! But I’d also like to display the final statusCode of the request to make it look like this

2018-10-15T20:29:18.321Z - info: ......127.0.0.1 > [200] [...GET] example.com.br/api/v1/carrinho

Thank you for your help!


#4

The middleware code you have written is executed before the controller method, then how come the status will exists?

You have to use the downstream block of the middleware to achieve this

async handle ({ request, response }, next) {
  await next()

  // called after controller
  console.log(response.response.statusCode)
}

#5

Thank you! When I use a downstream middleware, is there any situation where the middleware code will run before the route code is completed?


#6

Nope, it’s always after the route handler


#7

Ok! Thank you!