UnhandledPromiseRejectionWarning 在 nodejs 中出现类型错误

UnhandledPromiseRejectionWarning with type error in nodejs

当我在nodejs中运行节点server.js时,报错提示'Cannot read 属性 'length' of undefined'。我已经安装了所有相关的库(例如请求)并查看了不同的相关帖子。但是,问题仍然存在。 我认为它与 express 或 index 文件有关。 有什么建议吗? 非常感谢!

(node:14320) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
at pathtoRegexp (/home/floyd/Desktop/icigai/marketplace_backend/node_modules/path-to-regexp/index.js:63:49)
at new Layer (/home/floyd/Desktop/icigai/marketplace_backend/node_modules/express/lib/router/layer.js:45:17)
at Function.use (/home/floyd/Desktop/icigai/marketplace_backend/node_modules/express/lib/router/index.js:464:17)
at Function.<anonymous> (/home/floyd/Desktop/icigai/marketplace_backend/node_modules/express/lib/application.js:220:21)
at Array.forEach (<anonymous>)
at Function.use (/home/floyd/Desktop/icigai/marketplace_backend/node_modules/express/lib/application.js:217:7)
at _default (/home/floyd/Desktop/icigai/marketplace_backend/src/loaders/express.js:28:9)
at _callee$ (/home/floyd/Desktop/icigai/marketplace_backend/src/loaders/index.js:8:11)
at tryCatch (/home/floyd/Desktop/icigai/marketplace_backend/node_modules/regenerator-runtime/runtime.js:63:40)
at Generator.invoke [as _invoke] (/home/floyd/Desktop/icigai/marketplace_backend/node_modules/regenerator-runtime/runtime.js:293:22)

(node:14320) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)

编辑:

// express.js

import bodyParser from 'body-parser';
import cors from 'cors';
import multer from 'multer';

// API routes
import * as routes from '../api';

// const app = express(); // for itelisense only..

export default ({ app }) => {
    const env = process.env.NODE_ENV;
    /**
     * Enable cors on all actions
     */
    app.use(cors());

    /**
     * Transform string to JSON.
     */
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(multer({dest:'./uploads/'}).any());
    /**
     * SERVERS
     */
        
    app.use(process.env.ROUTING_PREFIX, routes.default);

    /**
     * Check API health.
     */
    app.get(`${process.env.ROUTING_PREFIX}status`, (req, res) => {
        res.status(200).send('SEQT IS UP AND RUNNING!');
    });

    /**
     * Catch 404 and forward to error handle.
     */
    app.use((req, res, next) => {
        const err = new Error('Not Found');
        err.status = 404;
        next(err);
    });

    /**
     * Global error catcher.
     */
    app.use((err, req, res, next) => {
        res.status(err.status || 500);
        res.json({
            errors: {
                message: err.message,
            },
        });
    });
};

// index.js

import expressLoader from './express';
import logger from './logger';

export default async ({ app }) => {
    /**
     * loads express essentials
    */
    await expressLoader({ app });
    logger.log('info', 'Express Loader has initialized successfully! ✅');
};

// server.js

// This is the one responsible for the Route Alias
import express from 'express';
import 'dotenv/config.js';

// This is used for logging
import logger from './loaders/logger';

require('module-alias/register');

const path = require('path');
require('dotenv').config({ path: path.join(__dirname, `../.env.${process.env.NODE_ENV}`) });

// This is the DB Sequelize instance
const sequelize = require('./sequelize');

// We are creating a function to use the Async & Await syntax
async function startServer() {
    const app = express();
    const port = process.env.PORT || 8888;

    app.use(express.static('./'));
    // Testing the DB Connections
    try {
        await sequelize.authenticate();
        logger.info('Connection has been established successfully.');
    } catch (error) {
        logger.error('Unable to connect to the database:', error);
    }

    // Import the express loaders (Packages)
    await require('./loaders').default({ app });

    app.listen(port, (err) => {
        if (err) {
            process.exit(1);
        }
        logger.info(`
        ################################################
              Server listening on port: ${port}  
        ################################################`);
    });
}

startServer();

undefinednull 值传递给 app.use 将导致显示的错误。所以我猜你的环境变量有问题,因为你正在使用例如:

app.use(process.env.ROUTING_PREFIX, routes.default);

尝试执行 console.log(process.env.ROUTING_PREFIX) 并检查值是否已设置或者它是 undefined