问题描述
这是我的问题。我有一个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}` },});