Bla*_*rov 4 javascript express reactjs axios next.js
所以这是我的问题。我有一个仪表板页面和程序页面。问题出在我有 SSR 的程序页面上,因为在仪表板页面上我在客户端调用我的传奇,并且一切都正常工作。
客户端:客户端将 httpOnly cookie 发送到我的后端服务器,并从我的后端获取数据以供使用。
服务器端:但是,由于某种原因,当我在 getServerSideProps 中调用相同的传奇时,当然 {withCredentials: true} 它不会出于某种原因将令牌发送到我的后端。在我从 req.headers.cookie 内的 getServerSideProps 获取的 req 对象内,我看到了 cookie,但它没有发送它。那么从 getServerSideProps 调用它时手动添加它的解决方案是什么?
代码:
export const getServerSideProps = wrapper.getServerSideProps(
async ({ store, req }) => {
store.dispatch(fetchprogramsRequest(req.url));
const cookies = cookie.parse(req.headers.cookie);
console.log('COOKIES', cookies); // HERE you can see the cookies
// end the saga
store.dispatch(END);
await store.sagaTask.toPromise();
}
);
The axios inside the saga:
const res = yield axios.get(url, { withCredentials: true });
This is called in both cases (client-side: works, server-side: doesn't)
Run Code Online (Sandbox Code Playgroud)
我相信cookie存储在客户端(浏览器)上。
也许这可行,只要你能让 cookie 到达传奇。
// The axios inside the saga:
const res = yield axios.get(url, {
headers: {
Cookie: "cookie1=value; cookie2=value; cookie3=value;"
});
Run Code Online (Sandbox Code Playgroud)
如果您使用访问令牌,另一种选择是像使用授权标头一样发送它。
const res = await axios.get(url, {
headers: { Authorization: `Bearer ${token}` },
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3471 次 |
| 最近记录: |