Core: How to prevent default html reponse on api only project errors?

Created on 24 Jul 2018  路  4Comments  路  Source: adonisjs/core

I'm starting an api only project with adonis, but every error returns as html content instead of json. For example, when a route is protected with the auth middleware and the token isn't passed, it returns the InvalidJwtToken error html page.

How can I prevent this behavior and return just json or avoid the default validation and check on my own to return json?

Most helpful comment

AdonisJs in built error handling respects the content negotiation headers like Accept.

If you will set the Accept: application/json header, then all error output will be in JSON over HTML.

Another thing you can do is create a global middleware, which set this header for you, this way your clients won't have to set the header explicitly.

Sample code for the middleware

class SpoofAccept {
  async handle ({ request }, next) {
    request.request.headers['accept'] = 'application/json'
    await next()
  }
}

module.exports = SpoofAccept

All 4 comments

AdonisJs in built error handling respects the content negotiation headers like Accept.

If you will set the Accept: application/json header, then all error output will be in JSON over HTML.

Another thing you can do is create a global middleware, which set this header for you, this way your clients won't have to set the header explicitly.

Sample code for the middleware

class SpoofAccept {
  async handle ({ request }, next) {
    request.request.headers['accept'] = 'application/json'
    await next()
  }
}

module.exports = SpoofAccept

Closing since no answer from issue reporter.

It did not solve the issue for me.

image

Request

image

Response

image

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

GianCastle picture GianCastle  路  3Comments

imperez picture imperez  路  4Comments

themodernpk picture themodernpk  路  3Comments

umaams picture umaams  路  3Comments

dezashibi picture dezashibi  路  4Comments