Cha*_*rge 3 json ruby-on-rails fetch reactjs
在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
Run Code Online (Sandbox Code Playgroud)
在我的正面,在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
}
Run Code Online (Sandbox Code Playgroud)
问题是我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
Run Code Online (Sandbox Code Playgroud)
我尝试返回简单的JSON文本,以防我的user变量出现问题,并尝试更改render json: user为format.json { render json: user }但没有结果:/
我在Postman上发出了请求,它返回了合适的JSON,所以我猜问题来自于我fetch?
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});
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1295 次 |
| 最近记录: |