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 : []
}