【发布时间】:2020-08-14 11:10:44
【问题描述】:
我正在获取一个访问 API 端点的令牌,我想将此令牌发送到我的服务器端应用程序 (expressJS) 以检索数据。
我的 react 应用程序有以下内容:
export default class Account extends React.Component {
constructor() {
super();
this.state = {
token: null,
response: {
}
};
this.getCurrentlyPlaying = this.getCurrentlyPlaying.bind(this);
}
componentDidMount() {
// Set token
let _token = hash.access_token;
if (_token) {
this.setState({
token: _token
});
const cookies = new Cookies();
cookies.set('token', _token, { path: '/' });
console.log(cookies.get('token'));
this.getCurrentlyPlaying(_token);
}
}
getCurrentlyPlaying() {
fetch(`http://localhost:3001/account`)
.then(res => res.json())
.then(data => {
this.setState ({
response: data
})
console.log(data);
});
}
render() {
if (this.state.response[0].is_playing === true) {
return (
<p> Something is playing</p>
);
}
else {
return (
<p> Nothing is playing</p>
);
}
}
}
在我的 express 应用程序中,我获取了 cookie,但我不确定它是否真的获取了 react 应用程序创建的 cookie:
router.get('/account', (req, res) => {
const config = {
headers: {
'Authorization': `Bearer ${req.session.token}`
}
};
fetch(`${CONFIG.spotifyUrl}/me/player/currently-playing `, config)
.then(html => html.json())
.then(json => {
res.json(json);
});
});
module.exports = router;
谁能告诉我哪里出错了?
【问题讨论】:
-
使用 document.cookie 设置 cookie。参考这个developer.mozilla.org/en-US/docs/Web/API/Document/cookie
-
@chandan_kr_jha 它正确设置了 cookie,因为当我有 cookie 的
console.log()时,我看到它显示了。我正在使用 'react-cookie- 包。 -
在 express js 的日志中看到了什么。请参阅stackoverflow.com/questions/44816519/…。你在 expressjs 中使用 cookie-parser。如果没有尝试第二个答案。 cookie 将在标题中。
-
我的 app.js 文件中有
app.use(cookieParser()); -
@chandan_kr_jha 我正在做类似问题中提到的事情,但它仍然无法为我获取。它也没有显示任何奇怪的错误
标签: reactjs express cookies token session-cookies