【发布时间】:2019-11-23 15:16:32
【问题描述】:
下面是我的保护路由,它使用 jwt 令牌来验证用户。我已经使用 Postman 测试了路线,我收到了正确的 id,名称。我想要实现的是使用 Fetch API 发送一个 GET 请求以获取此数据并将其显示在我在反应文档中找到的 Profile 组件上。我还包括了我的尝试方法,但欢迎所有建议。
{
"id": 8,
"name": "Kie",
"iat": 1563135959,
"exp": 1563137399
}
/我的路线
router.get('/me', function(req, res) {
var token = req.headers['x-access-token'];
if (!token)
return res.status(401).send({ auth: false, message: 'No token provided.' });
jwt.verify(token, secret, function(err, decoded) {
if (err)
return res
.status(500)
.send({ auth: false, message: 'Failed to authenticate token.' });
res.status(200).send(decoded);
});
});
配置文件组件
import React, { Component } from 'react';
import jwt_decode from 'jwt-decode';
class Profile extends Component {
constructor() {
super();
this.state = {
Items: [],
hasErrored: false,
isLoading: false
};
}
componentDidMount() {
fetch('http://localhost:5000/api/me')
.then(response => {
if (!response.ok) {
throw response;
} // Return the complete error response for debugging purposes
return response.json(); //we only get here if there is no error
})
.then(json => {
this.setState({ Items: json.Items });
});
// .catch(error => {
// () => this.setState({ hasErrored: true, error }); // Save both error flag and error detail so you can send it to tools like bugsnag
// / });
}
render() {
// if (this.state.hasErrored) {
// return <p>There was an error loading the items</p>;
// }
if (this.state.isLoading) {
return <p>Loading...</p>;
}
return (
<div>
<ul>
{this.state.Items.map(item => (
<li key={item.ID}></li>
))}
</ul>
</div>
);
}
}
export default Profile;
【问题讨论】:
-
会发生什么?查看浏览器中的开发人员工具。查看控制台。是否报告了任何错误消息?查看网络选项卡。你看到请求了吗?它的格式是否符合您的预期?它得到回应了吗?它的格式是否符合您的预期?
-
赌这是stackoverflow.com/a/35553666/19068的另一个副本
-
@Quentin 你有什么建议这么多信息哈哈
-
当我回到我的笔记本电脑时,我会尽快回答你的问题