所以这是我的问题。我有一个仪表板页面和程序页面。问题出在我有 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 …Run Code Online (Sandbox Code Playgroud) 所以首先我用 baseurl 创建自定义 axios 实例并像这样导出它:
import axios from 'axios';
const instance = axios.create({
baseURL: process.env.BACKEND_URL,
});
instance.defaults.headers.common['Authorization'] = 'AUTH TOKEN';
instance.defaults.headers.post['Content-Type'] = 'application/json';
export default instance;
Run Code Online (Sandbox Code Playgroud)
导入此自定义 axios 实例时,问题出在我的传奇或任何组件中(仅限客户端)。我使用 next-redux-wrapper,当我为我的组件预取数据(使用 getStaticProps)时,一切正常,并且 axios.defaults.baseURL 属性工作正常。然而,问题出在客户端,每当我在任何组件或 saga 中导入相同的 axios 实例但我从让我们说 componentDidMount 调用它时,相同的 axios.default.baseURL 是未定义的,所以如果我想发出请求我必须输入完整的后端 + 查询 URL。可能是什么问题?例子:
export function* fetchTPsSaga() {
try {
console.log(axios.defaults.baseURL);
const url = `/training-programs`;
const res = yield axios.get(url);
const tPs = res.data.data;
yield put(fetchTrainingProgramsSuccess(tPs));
} catch (err) {
yield put(fetchTrainingProgramsFail(err));
}
}
Run Code Online (Sandbox Code Playgroud)
// 第一次渲染(在服务器端),它是有效的 baseURL 属性,但是如果我从客户端调用相同的 saga(当组件被渲染时)它是未定义的,所以我必须输入完整的 url