[JavaScript] I can't get the response body at the time of error with axios (ajax)

Introduction

It was a blind spot, so make a note. When I posted to Rails API from the front and got an error, I wanted to put a detailed message in the response body and return it.

Ruby on Rails

if user.save
  render json: { status: 200, data: user }
else
  render  status: :unprocessable_entity, json:{ messages: user.errors.full_messages }
end

JavaScript

axios
  .post(process.env.API_URL + '/api/v1/users/signup')
  .then((res) => {
    console.log(res)
   })
  .catch((e) => {
    console.log(e)
   })

result

Error: Request failed with status code 422
    at createError (createError.js?2d83:16)
    at settle (settle.js?467f:17)
    at XMLHttpRequest.handleLoad (xhr.js?b50d:69)

I can't get the error response body ...


approach

I was wondering if I couldn't return the rails error, but the problem was the front desk. You can access the error response as follows

  .catch((e) => {
    console.log(e.response.data.messages)
   })

When it is 200, it returns an Object, but ...

{data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}

Summary

I had turned my spear to the back end because I was not good at it, but the front ability was still not good. .. .. When I hit the wall, I felt once again that I should abandon the rules and carefully search for the cause one by one.

Recommended Posts

[JavaScript] I can't get the response body at the time of error with axios (ajax)
I can't get out of the Rails dbconsole screen
About the behavior at the time of error of Files.copy (pathA, pathB)
[Rails] Get access_token at the time of Twitter authentication with Sorcery and save it in DB
[Rails] About Uglifier :: Error: Unexpected token: at the time of deployment
Email sending function with Action Mailer at the time of new registration
I was stuck with the handling of the time zone when formatting with SimpleDateFormat
When I renew the certificate with CircleCI × fastlane, I get an exit status: 65 error.
[JavaScript] I want to limit the processing by checking the input items when the specified time elapses at the time of focus out.
Get Body part of HttpResponse with Filter of Spring
I checked the number of taxis with Ruby
I tried to create a log reproduction script at the time of apt install
At the time of dialogReturn event, I checked because it is not updated even if I specify a component with update
[Swift] Get the number of steps with CMP edometer
I get Mysql2 :: Error :: ConnectionError in the production environment
Speed comparison at the time of generation at the time of date conversion
I summarized the display format of the JSON response of Rails
[Rails] What to do if you can't get an error message with the errors method
Whether to make the server side at the time of system rebuild with Kotlin or Java