HttpOnly cookie未从使用axios(withCredentials:true)的next js getServerSideProps发送

4

这是我的问题。我有一个仪表板页面和一个程序页面。问题出在程序页面,因为我使用了SSR,而在仪表板页面上,我在客户端调用我的saga,一切都运作正常。

客户端:客户端向后端服务器发送httpOnly cookie,并从后端获取数据供使用。

服务器端:但是由于某些原因,在getServerSideProps中调用相同的saga时,当然会使用{withCredentials: true},它不会将令牌发送到后端。在getServerSideProps中获得的req对象内,通过req.headers.cookie可以看到cookie,但是它不会发送它。那么手动添加它的解决方案是什么?还是其他方法?

代码:

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)

1个回答

5

我相信cookie被存储在客户端(浏览器)上。

只要您能使cookie到达saga,这可能会起作用。

// The axios inside the saga:
const res = yield axios.get(url, {
    headers: {
        Cookie: "cookie1=value; cookie2=value; cookie3=value;"
    });

如果您正在使用访问令牌,则另一个选项是像使用授权头那样发送它。
 const res = await axios.get(url, {
      headers: { Authorization: `Bearer ${token}` },
    });

谢谢你。我能想到的方法也只有这两个了。 - Blagoj Petrov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接