API Rails 上的获取请求不返回 json

IT技术 ruby-on-rails json reactjs fetch
2021-05-03 17:34:22

在 Rails API 中,我的 UsersController 中有一个登录 POST 方法,它接受 2 个参数(邮件和密码),如果找到记录,则检查数据库,如果找到,则将其作为 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 调用此方法,该方法以表单形式获取邮件和密码值,并希望在我的 JSON 中包含用户'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)

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: userformat.json { render json: user }但没有结果:/

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

1个回答

Fetch 的响应不会自动转换为 JSON,您需要调用response.json()(返回Promise)才能获取 JSON 值。从 MDN查看这个例子,或者这里有一些 ES6 来匹配你的代码:

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