在 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: user
为format.json { render json: user }
但没有结果:/
我在 Postman 上提出了请求,它返回了适当的 JSON,所以我猜问题出在我的fetch
?