NodeJS:未处理的承诺拒绝警告

时间:2020-12-22 01:16:00

标签: javascript node.js express

每次我运行 npm run start 时,一切似乎都很正常,我的日志显示没有任何问题,直到我遇到这个:

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

(\node_modules\regenerator-runtime\runtime.js:293:22)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:4476) 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)
(node:4476) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
[nodemon] clean exit - waiting for changes before restart

我检查了 /loaders/express.js 和 /loaders/index.js 是否有可能的错误,但仍然没有任何线索:

// 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.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 from 'dotenv/config';

// 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();

我认为这与模块有关,所以如果有人能告诉我我的代码中可能出了什么问题,那就太好了

1 个答案:

答案 0 :(得分:0)

   TypeError: Cannot read property 'length' of undefined

错误很明显。在您的代码中的某处(您应该将其发布在问题中),您可能有这样的内容。

const something= async operation
const new      = something.length // since you are not waiting for the async operation to be resolved, something is "undefined". in the next line, you end up having "undefined.length"

看来您并没有在等那个async operation

 const something= await async operation // you should use `async` keyword in front of function. and it should be inside try, catch block

或:

 const something= (async operation).then((result)=>{

   // after your async operation resolved, you work with that 
 })