我目前正在使用 axios 和 NextJS。
我目前在我的组件中有这个代码:
export async function getServerSideProps(context) {
const data = await getVideo(context.query.id);
console.log('data: ', data);
// console.log('context: ', context);
console.log('context params: ', context.params);
console.log('context query: ', context.query);
if (!data) {
return { notFound: true };
}
return {
props: {
videoId: context.params.id,
videoSlug: context.params.slug,
videoContent: data
}
};
}
这个 getserverSideProps 调用的函数getVideo
看起来完全像这样:
export const getVideo = (id) => async (dispatch) => {
dispatch({ type: CLEAR_VIDEO });
try {
console.log('Action file: ', id);
const res = await api.get(`/videos/${id}`);
return dispatch({
type: GET_VIDEO,
payload: res.data
});
} catch (err) {
dispatch({
type: VIDEO_ERROR,
payload: { msg: err.response?.statusText, status: err.response?.status }
});
}
};
所述函数通过我的 api 函数向后端发出请求:
import axios from 'axios';
import { LOGOUT } from '../actions/types';
import { API_URL } from '../config';
const api = axios.create({
baseURL: `${API_URL}/api/v1`,
headers: {
'Content-Type': `application/json`
}
});
/**
intercept any error responses from the api
and check if the token is no longer valid.
ie. Token has expired
logout the user if the token has expired
**/
api.interceptors.response.use(
(res) => {
res;
console.log('Res: ', res.data);
},
(err) => {
if (err?.response?.status === 401) {
typeof window !== 'undefined' &&
window.__NEXT_REDUX_WRAPPER_STORE__.dispatch({ type: LOGOUT });
}
return Promise.reject(err);
}
);
export default api;
它在执行 POST、PUT、PATCH 请求时效果很好。
如您所见,我正在做一个console.log('data: ',data)
,但[AsyncFunction (anonymous)]
每当我阅读终端时它都会返回;另一方面,前端返回此错误:
服务器错误错误:从“/videos/[id]/[slug]”中
.videoContent
返回的 错误序列化。getServerSideProps
原因:function
无法序列化为 JSON。请仅返回 JSON 可序列化数据类型。
有谁知道如何解决这个问题?
注意:我正在使用 react-redux、redux 和 next-redux-wrapper。