如何解决Next.js 如何在 getInitialProps 中向客户端发送 200 状态
如果我收到没有 getMainPage 请求内容的状态 200,我需要将状态从服务器传输到客户端。我怎样才能做到这一点? 我试过(来自谷歌的例子):
if (ctx.res) ctx.res.statusCode = 404;
return {notFound: true};
ctx.res 总是 = 未定义
/主页.ts/
IndexPage.getinitialProps = async (ctx: IExtendedAppContext): Promise<IPageProps> => {
const { reduxStore } = ctx;
const regionId = reduxStore.getState().regions.current?.id;
const cityId = reduxStore.getState().regions.current?.city;
const transaction = apm?.startTransaction('IndexPage');
const main: IMain = await reduxStore.dispatch(getMainPage({ region: regionId,city: cityId },transaction));
const span = startSpan('fetchAlphabetList',transaction);
const alphabetList = await alphabetListService.fetch({ region: regionId,city: cityId })
.finally(() => endSpan(span));
endTransaction(transaction);
return { pageMeta: main.page_Meta,alphabetList };
};
/with-redux-store.tsx/
export type Store = ReturnType<typeof getorCreateStore>;
interface IProps {
reduxStore: Store;
initialReduxState: Store;
}
export interface IExtendedAppContext extends NextPageContext {
reduxStore: Store;
}
export interface IInitialProps extends AppContext {
ctx: IExtendedAppContext;
}
getMainPage 请求和所有 get 请求都使用该 get 方法
public async get(entity: string,query: object,pathVariables: string[] | number[] = [],cookies: string = '') {
const queryURI = makeURIParams(query);
const key = makeQueryKey(entity,query,pathVariables);
try {
const localcopy = await this.getLocalcopy(key);
return this.handleResponse(localcopy);
} catch (error) {
console.log(this.getUrlAPI(entity,queryURI,pathVariables));
return this.fetch(this.getUrlAPI(entity,pathVariables),{headers: {...this.getCookies(cookies)}})
.then(this._httpHandler).then(async (dataJSON: any) => {
try {
const { Meta = {} } = dataJSON;
Meta.requestDate = getCurrentTime();
const { expire,date } = Meta;
if (expire <= date) {
await this.purgeStorageByKey(key);
return dataJSON;
}
if (expire !== 0) await this.setLocalcopy(key,JSON.stringify(dataJSON));
return dataJSON;
} catch (error) {
console.log(this.getUrlAPI(entity,error);
return null;
}
}).then(this.handleResponse).catch((error: Error) => {
console.log(this.getUrlAPI(entity,error);
return null;
});
}
}
private _httpHandler(response: Response): Promise<IResponse | null> {
return new Promise(async (resolve,reject) => {
if ((response.status >= 200 && response.status < 300) || response.status === 403) {
try {
const json = await response.json();
resolve({ requestUrl: response.url,responseHeaders: response?.headers,...json });
} catch (_) {
resolve(null);
}
} else {
reject(response.statusText);
}
});
}
解决方法
所以如果它是异步函数并返回值,您可以检查状态,
let mainResponseStatus = false;
if (main.status === 200) {
mainResponseStatus = true;
}
然后继续你的代码并返回你想要的任何东西,但作为回报保护它
return {
somethingToReturn: mainResponseStatus ? returnWhatYouWant : []
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。