首页 > 解决方案 > Next.js 如何在 getInitialProps 中向客户端发送 200 状态

问题描述

如果我收到状态 200 而没有 getMainPage 请求的内容,我需要将状态从服务器传输到客户端。我怎样才能做到这一点?我试过(来自谷歌的例子):

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, queryURI, 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, queryURI, pathVariables), error);
                    return null;
                }
            }).then(this.handleResponse).catch((error: Error) => {
                console.log(this.getUrlAPI(entity, queryURI, pathVariables), 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);
            }
        });
    }

标签: reactjstypescriptxmlhttprequestnext.js

解决方案


所以如果它是异步函数并返回值,你可以检查状态,

let mainResponseStatus = false;
    if (main.status === 200) {
     mainResponseStatus = true;
    }

然后继续您的代码并返回您想要的任何内容,但作为回报进行防御

return {
    somethingToReturn: mainResponseStatus ? returnWhatYouWant : []
}

推荐阅读