不会使用axios从下一个js getServerSideProps发送HttpOnly cookiewithCredentials:true

问题描述

这是我的问题。我有一个dasboard页面,我有程序页面。 问题出在我拥有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)

解决方法

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

只要您可以使Cookie达到传奇,这可能就可以了。

// 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}` },});

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...