【问题标题】:HttpOnly cookie is not sent from next js getServerSideProps using axios (withCredentials: true)HttpOnly cookie 不使用 axios 从下一个 js getServerSideProps 发送(withCredentials:true)
【发布时间】:2020-11-30 12:16:56
【问题描述】:

所以这是我的问题。我有一个仪表板页面,我有程序页面。 问题出在我有 SSR 的程序页面上,因为在仪表板页面上,我在客户端调用我的 saga,一切正常。

客户端:客户端将 httpOnly cookie 发送到我的后端服务器,并从我的后端获取数据以供使用。

服务器端:但是由于某种原因,当我在 getServerSideProps 中调用相同的 saga 时,当然 {withCredentials: true} 它不会出于某种原因将令牌发送到我的后端。在我从 req.headers.cookie 中的 getServerSideProps 获得的 req 对象中,我看到了 cookie,但它没有发送它。那么在getServerSideProps或者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)

【问题讨论】:

    标签: javascript reactjs express axios next.js


    【解决方案1】:

    我相信 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}` },
        });
    

    【讨论】:

    • 是的,tyvm。我能想到的唯一方法也是那些 2..
    猜你喜欢
    • 2021-11-03
    • 2020-11-19
    • 1970-01-01
    • 2021-08-26
    • 2021-08-05
    • 2021-05-22
    • 2021-08-04
    • 2019-01-27
    • 2017-06-20
    相关资源
    最近更新 更多