NextJS:TypeError:无法读取未定义的属性“标题”

我在附加到我的页面的 getInitialProps 函数中收到此错误:

const getInitialProps = async ({ req, query }: NextPageContext) => {
  let isValidReferenceQuery = true;

  const { path } = absoluteUrl(req as IncomingMessage);
  try {
    await policyService.getPolicyByReference(
      path,
      query.referenceQuery as string
    );
  } catch (error) {
    isValidReferenceQuery = false;
  }

  return {
    referenceQuery: (query.referenceQuery as string) ?? null,
    isValidReferenceQuery,
  };
};

Page.getInitialProps = getInitialProps;

函数 absoluteUrl 确定 API 调用是在服务器端还是客户端进行,并相应地调整路径:

export default function absoluteUrl(
  req: IncomingMessage
): Record<string, string> {
  const protocol = req.headers.referer?.split('//')[0] ?? 'http:';
  const host = req
    ? req.headers['x-forwarded-host'] || req.headers.host
    : window.location.host;
  const path =
    host === 'localhost:3000'
      ? `${protocol}//localhost:8080`
      : `${protocol}//${host}${axios.defaults.baseURL}`;
  return {
    path,
  };
}

我已经更新了我的 _document.tsx_app.tsx 以包含 getInitialProps 以在开发模式下选择退出自动静态生成,因此应该定义 req 。我们还需要所有页面都是 SSR 以进行本地化:

import React from 'react';
import App, { AppContext } from 'next/app';
import { ReactQueryCacheProvider, QueryCache } from 'react-query';
import { Hydrate } from 'react-query/hydration';
import { appWithTranslation } from '@/localisation/i18n';
import { AppPageProps } from '@/models/page';

const TextMiningApp = ({ Component, pageProps }: AppPageProps) => {
  const queryCache = new QueryCache();
  const Layout = Component.Layout ? Component.Layout : React.Fragment;

  return (
    <ReactQueryCacheProvider queryCache={queryCache}>
      <Hydrate state={pageProps.dehydratedState}>
          <Layout>
            {/* eslint-disable-next-line react/jsx-props-no-spreading */}
            <Component {...pageProps} />
          </Layout>
      </Hydrate>
    </ReactQueryCacheProvider>
  );
};

TextMiningApp.getInitialProps = async (appContext: AppContext) => ({
  ...(await App.getInitialProps(appContext)),
});

export default appWithTranslation(TextMiningApp);

我不明白为什么如果我选择退出 req 未定义的自动静态生成?

stack overflow NextJS: TypeError: Cannot read property 'headers' of undefined
原文答案

答案:

作者头像

不确定这是否仍然需要,但目前 getInitialProps 中的 _app.js 实际上与页面略有不同。它不是直接将上下文作为参数传递,而是传递具有 ctxComponent 属性的对象。所以你需要做这样的事情:

TextMiningApp.getInitialProps = async( { ctx, Component } ) => {
  // This should be working now.
  console.log( ctx.req );
}

一个问题是 App.getInitialProps 它需要从原始参数传递所有属性:

App.getInitialProps( ctx, Component );

参见 https://github.com/vercel/next.js/discussions/14913

相关问题