reactjs - 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);
}
});
}
解决方案
所以如果它是异步函数并返回值,你可以检查状态,
let mainResponseStatus = false;
if (main.status === 200) {
mainResponseStatus = true;
}
然后继续您的代码并返回您想要的任何内容,但作为回报进行防御
return {
somethingToReturn: mainResponseStatus ? returnWhatYouWant : []
}
推荐阅读
- python - `python -m app` 无法打开串口但 `flask run` 工作
- mysql - Mysql从一个文件夹导入多个CSV和SQL
- amazon-web-services - AWS 无服务器框架 Mono-Repo 结构最佳实践
- apache-flink - Flink Hash Join 超出最大递归数错误
- python - 在 pyspark 流中从 Dstream 展平列表/数组
- javascript - 为什么没有出现控制台
- google-sheets - 使用 Query 和 Importrange 时的公式解析错误
- go - 是否有可能知道哪些 go 包安装在二进制文件中
- ruby-on-rails - 第一次创建后如何将我的模型配置为只读
- javascript - JavaScript - 查找所有具有类的元素,查找重复项并显示它们