在Rails API中,我在UsersController中有一个登录POST方法,它接受2个参数(邮件和密码),如果找到记录则检入DB,如果是,则返回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:
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
?
答案 0 :(得分:6)
Fetch的响应没有自动转换为JSON,您需要调用response.json()
(返回一个promise)以获取JSON值。请参阅this example from 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});
}
});