【发布时间】:2018-06-17 21:32:57
【问题描述】:
我正在尝试打印 Fetch 承诺的值,但是当我 console.log 时它显示 undefined。
当我在 Postman 中尝试时,Php 服务器会在 http 正文中使用 jwt 令牌响应此获取。
fetch("http://localhost:8001/api/login", {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'username=' + this.state.username + '&password=' + this.state.password
})
.then(function (responseObject) {
console.log('Request succeeded with Response object', responseObject);
})
.then(function (result){
console.log(result);
})
.catch(function (error) {
console.log('Request failed', error);
});
}else{
console.log('You must enter username, password.');
}
【问题讨论】:
-
你的第一个 .then 没有返回语句,所以返回
undefined...这就是为什么第二个 .then 的结果是未定义的。尝试在您的第一个 .then 中返回responseObject.text()或responseObject.json() -
通过将
return responseObject添加到第一个来解决问题。 then 子句和 `console.log(responseObject.text());到第二个 .then 子句,现在我的 jwt 令牌打印出来了。谢谢@Jaro
标签: javascript reactjs promise fetch-api