API Rails上的提取请求未返回json [英] Fetch request on API Rails doesn't return json

查看:64
本文介绍了API Rails上的提取请求未返回json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails API中,我的UsersController中有一个登录POST方法,该方法带有2个参数(邮件和密码),并在DB中检查是否找到记录,如果找到,则将其返回为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

在我的前端,在React中,我使用fetch调用此方法,该方法以某种形式获取邮件和密码值,并希望在'res'中将用户作为JSON:

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

  }

问题是我的res与我用render json: user返回的内容不对应,所以我做了一个console.log(res):

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

我尝试返回简单的JSON文本,以防我的user变量出现问题,并且还尝试将render json: user更改为format.json { render json: user },但没有结果:/

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 :/

我在Postman上发出了请求,它返回了合适的JSON,所以我猜问题出在我的fetch上?

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

推荐答案

Fetch的响应不会自动转换为JSON,您需要调用response.json()(它返回一个Promise)以获取JSON值.请参见来自MDN的示例,或者这是一些与您的代码匹配的ES6:

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});
    }
  });

这篇关于API Rails上的提取请求未返回json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆