0
votes

I've got a Laravel Lumen 7 RESTful API alongside a Nuxt JS front-end with Axios. My front-end makes Axios calls to the API and inside of my Lumen project I'm of course returning relevant responses and error codes. However, it appears that these responses although I can see them when I inspect the network and can see it in the preview/response tabs, I'm unable to access it from Axios in my catch() block...

If I change it to a 200 response then I can access it from my then() block but this isn't ideal.

Lumen response

return response()->json(['success' => false, 'message' => 'We\'re unable to add this domain right now, please try again shortly'], 500);

JS Axios function

/*
** Add domain
*/
addDomain () {

  // add new domain
  this.$axios.post(`${process.env.API_URL}/api/domains/add`, this.domainCreation).then(res => {
    console.log(res)
  }).catch(err => {
    console.log(err) // doesn't display my Object from laravel, instead just the native error string: "Error: Request failed with status code 500"
  })

}

Can anyone help?

2
Change status code to one of 4xx codes. Also err.response. 500 is reserved for server config errors and you application probably thinks your backend encountered a config error. My 2 cents.user3532758

2 Answers

4
votes

try this err.response catch error data is inside response

this.$axios.post(`${process.env.API_URL}/api/domains/add`, this.domainCreation).then(res => {
    console.log(res)
  }).catch(err => {
    console.log(err.response);
  })

ref link https://github.com/axios/axios#handling-errors

0
votes

In addition to the above answer, you should consider returning the correct response codes.

5xx error codes are for Internal Server Errors. You are probably looking to return a 422 unprocessable entity error.

More info about 500 status code: https://httpstatuses.com/500

More info about 422 status code: https://httpstatuses.com/422