【发布时间】:2019-01-30 09:17:42
【问题描述】:
我正在构建一个同构/通用的 React + Redux + Express 应用程序。我的服务器端数据获取非常标准:我查看哪些路由与 URL 匹配,调用所有返回承诺的相关数据获取方法,然后等待它们解析并呈现 HTML。
我的挑战:某些 API 调用需要身份验证。登录的用户有一个 cookie,当然会随每个请求一起发送。但是,当我在服务器端进行数据获取以填充存储以进行初始渲染时,我的 API 调用无法使用 cookie。我该如何做到这一点?
// server-entry.jsx
app.get('*', (req, res) => {
const store = createStore(
combineReducers({
// lots of reducers
}),
{},
applyMiddleware(thunk),
);
/*
The contents of getDataFetchers isn't important. All you need
to know is it returns an array of data-fetching promises like so:
dispatch(thunkAction());
*/
const fetchers = getDataFetchers(req.url, store);
Promise.all(fetchers).then(() => {
// render the tree
});
});
// one of my thunk actions hits an API endpoint looking like this:
app.get('/api', (req, res) => {
// this is simplified, but you get the idea:
// we need access to the cookie to authenticate
// but when this call is made server-side, req.session.user doesn't exist
if (!req.session.user) res.status(403);
else res.json({ data: 'here' });
});
我想我可以从 app.get 中的 req 获取 cookie,并将其作为参数一直传递到实际数据获取(使用 axios 完成),其中将使用 @987654325 指定@标头。但这感觉很恶心。
【问题讨论】:
标签: javascript reactjs express redux isomorphic-javascript