Nextjs无法加载主页



我正在使用Nextjs创建一个网站。但当我在本地运行它时,它不会在控制台上加载任何内容,只显示[ event ] build page: /_error。我试图记录_error.js,但没有显示任何内容。以下是我的配置:

server/index.js

// Use dotenv Config Package
const dotenv = require('dotenv');
// Express Package and Next Package For Run server
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const next = require('next');
const nextI18NextMiddleware = require('next-i18next/middleware').default
dotenv.config();
const NextI18NextInstance = require('../i18n');
const port = parseInt(process.env.PORT, 10) || 3000; // Port Application Run Load From dotenv File
const dev = process.env.NODE_ENV !== 'production'; // Application Run Environment Load From dotenv File
const app = next({ dev }); // Add Loaded Config to Application
const handle = app.getRequestHandler();
const proxyOptions  = {
    target: process.env.API_PROXY_URL + ':' + process.env.API_PROXY_PORT,
    changeOrigin: true,
    ws: true,
};
const devProxy = createProxyMiddleware(proxyOptions);
app.prepare()
    .then(() => {
        // Run Express Server
        const server = express();
        server.use(nextI18NextMiddleware(NextI18NextInstance));
        server.use('/api', devProxy);


        // Handle All Server Requests And Responses
        server.all('*', (req, res) => {
            return handle(req, res);
        });
        // Server Listen Port Config
        server.listen(port, err => {
            if (err) throw err;
            console.log(`> Ready on http://localhost:${port}`);
        });
    })
    // Application Catch Error On Run Server
    .catch(ex => {
        console.error(ex.stack);
        process.exit(1);
    });

i18n.js

// Import Next i18n Package
const NextI18Next = require('next-i18next').default;
// Create and Export Default i18n Config Module use in Whole Project
const languages = ['fa-IR', 'en-US'];
const options = {
    defaultLanguage: 'fa', // Default Language
    otherLanguages: ['en'], // Other Languages Can Add In Array
    // browserLanguageDetection: true, // Detect Language From Browser Meta
    defaultNS: 'common', // Default File Load in Ns
    localeExtension: 'json', // Default language Files Extension
};
const NextI18NextInstance = new NextI18Next(options);
NextI18NextInstance.i18n.languages = languages;
module.exports = NextI18NextInstance;

pages/index.js

import React, { Component } from 'react';
import {SiteLayout} from '../components';
import { i18n,withTranslation } from '../i18n'
class MainPage extends Component {
    render() {
        return (
            <SiteLayout pageTitle={'صفحه اصلی'}>
                {this.props.t('mainPage')}
            </SiteLayout>
        );
    }
}
MainPage.getInitialProps = async () => ({
    namespacesRequired: ['MainPage'],
});
export default withTranslation('MainPage')(MainPage);

在服务器启动并显示> Ready on http://localhost:3000之后,我在终端中得到了以下输出,浏览器在加载页面时卡住了。如果您需要更多信息,请询问。有什么想法如何调试或修复它吗?提前谢谢。

[HPM] Proxy created: /  -> https://myapi**.com:
> Ready on http://localhost:3000
[ event ] build page: /_error

如何解决?首先,我试图删除node_modules并重新安装它们,但没有成功。之后,我将next.js版本11升级为版本12,编译效果良好。您可以在这里查看文档升级过程

试着看看这个问题(Next.js开发服务器在一段时间后被卡住,请求只是旋转(,有几种方法。按照此解决方案,通过更改端口号解决了I问题。

对我来说,问题是nodejs 的旧版本

对于nextjs v13,最小节点版本是v16。但是,我使用的是v14。因此,我刚刚获得了以下关于运行next dev:的日志

> started server on 0.0.0.0:3000, url: http://localhost:3000
>  Loaded env from /Users/deepak/my-web-app/.env

有了这个节点版本,浏览器不断加载,浏览器或终端上没有任何错误。

但是,在切换到节点v16后,我终于得到了以下日志,之后应用程序运行良好:

> wait  - compiling / (client and server)...
> event - compiled client and server successfully in 3s (13135 modules)

对我来说,这个问题真的很奇怪。当我运行lsof -i tcp:3000时,有一个节点实例正在运行(可能是NextJs(,但当我运行npm run dev时,我没有收到错误。NextJs的开局不错。不知怎么的,我同时运行了两个NextJs实例,所以当我试图达到127.0.0.1:3000时,它就是无法加载。我终止了这个过程,问题就解决了。

如果您使用windows WSL。首先检查这个

如果不起作用将此作为最后一个选项

wsl2更改为wsl1为我解决了这个问题(我不知道为什么(!

您可以在PowerShell上使用以下代码:

wsl --set-version Ubuntu 1

尝试删除.next文件夹并运行npm run dev,它应该可以

今天我也面临这个问题,我花了几个小时才弄清楚,我的false在next.config.js文件中。请检查一下它是否能帮到你。

const path = require("path");
const subFolder = 'src';
module.exports = {
    webpack: config => {
        config.node = {
            fs: "empty"
        };
        // You can see MANY IMPLEMENTED ALIASES when printing this:
        console.log(config.resolve.alias);
        // So if you want to add your own aliases, don't replace the old one:
        // PLEASE DON'T DO THIS >>>
        // config.resolve.alias = {
        //     "@components": path.join(__dirname, "components"),
        //     "@pages": path.join(__dirname, "pages"),
        //     "@redux": path.join(__dirname, "redux"),
        //     "@api": path.join(__dirname, "api")
        // };
        // <<< PLEASE DON'T DO THIS

        // DO THIS INSTEAD >>>
        config.resolve.alias = {
            ...config.resolve.alias // <<< ADD THIS LINE to extend the old one
            "@components": path.join(__dirname, "components"),
            "@pages": path.join(__dirname, "pages"),
            "@redux": path.join(__dirname, "redux"),
            "@api": path.join(__dirname, "api")
        };
        // <<< DO THIS INSTEAD
      return config;
    },
};

最新更新