Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch request on API Rails doesn't return json

In a Rails API, I have a login POST method in my UsersController which takes 2 parameters (mail and password) and check in DB if a record is found and if so returns it as JSON.

  def login(mail, password)
    mail, password = params.values_at(:mail, :password)
    user = User.where(mail: mail, password: password)
    render json: user
  end

In my front side, in React, I call this method with fetch which takes the mail and password values in a form and expect to have the user as JSON in my 'res':

  login = () => {
    if(this.state.mail != null && this.state.password != null){
        fetch('http://127.0.0.1:3001/api/login', {
            method: 'post',
            body: JSON.stringify({
                            mail: this.state.mail,
                            password: this.state.password
                        }),
            headers: {
                'Accept': 'application/json',
                'Content-type': 'application/json'
            }
        })
        .then((res) => {
            console.log(res)
            if(res.data.length === 1 ){
                const cookies = new Cookies();
                cookies.set('mercato-cookie',res.data[0].id,{path: '/'});
                this.setState({redirect: true})
            }
        })
    }    bodyUsed: false
headers: Headers {  }
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://127.0.0.1:3001/api/login"
__proto__: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … } auth.js:32

  }

Problem is my res doesn't correspond to what I return with render json: user, so I made a console.log(res) :

Response
bodyUsed: false
headers: Headers {  }
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://127.0.0.1:3001/api/login"
__proto__: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … } auth.js:32

I tried returning simple JSON text in case there was a problem with my user variable and also tried changing render json: user to format.json { render json: user } but with no result :/

I made the request on Postman and it returns the appropiate JSON, so i guess the problem comes from my fetch ?

like image 293
Charles Duporge Avatar asked Mar 08 '23 02:03

Charles Duporge


1 Answers

Fetch's response doesn't automatically translate to JSON, you need to call response.json() (which returns a promise) in order to get the JSON value. See this example from MDN, or here's some ES6 to match your code:

fetch(myRequest)
  .then(response => response.json())
  .then((data) => {
    // I'm assuming you'll have direct access to data instead of res.data here,
    // depending on how your API is structured
    if (data.length === 1) {
      const cookies = new Cookies();
      cookies.set('mercato-cookie', data[0].id, {path: '/'});
      this.setState({redirect: true});
    }
  });
like image 51
carpeliam Avatar answered Mar 10 '23 13:03

carpeliam