How to resolve UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined

How to resolve UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined

我正在学习 Nodejs,我正在尝试实现 Promise 概念。 当我 运行 我的应用程序出现以下异常时:

Example app listening on port 3000!
TypeError: Cannot read property 'query' of undefined
    at D:\nodesjapp\rsrest-api\helpers\query.js:10:8
    at new Promise (<anonymous>)
    at module.exports (D:\nodesjapp\rsrest-api\helpers\query.js:1:45)
    at D:\nodesjapp\rsrest-api\app-middlewares\auth.js:30:22
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:5576) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined

我的查询助手是 query.js:

   module.exports = async (conn, q, params) => new Promise(
    (resolve, reject) => {
      const handler = (error, result) => {
          if (error) {
          reject(error);
          return;
        }
        resolve(result);
      }
      conn.query(q, params, handler);
    }).catch(console.log);

我调用这个登录API,它写在auth.js:

 const express = require('express');
    const connection = require('../helpers/connection');
    const query = require('../helpers/query');    
    const router = express.Router();
    const dbConfig = require('../dbConfig');    
    const create = require('../crud/create');
    
    router.post('/login', async (req, res) => {
      const { username, password } = req.body;
      const conn = await connection(dbConfig).catch(e => {});
      const user = await query(
        conn,
        `SELECT id, username FROM USERS WHERE username=? AND password=MD5(?)`,
        [username, password]
      );
      res.send(user[0] || { id: null, username: null });
    });    
    module.exports = router;

我的数据库配置写在dbConfig.js:

const dotenv = require("dotenv") 
dotenv.config();
// Get the Host from Environment or use default
const host = process.env.DB_HOST || 'localhost';
// Get the User for DB from Environment or use default
const user = process.env.DB_USER || 'root';
// Get the Password for DB from Environment or use default
const password = process.env.DB_PASS || 'root';
// Get the Database from Environment or use default
const database = process.env.DB_DATABASE || 'twitter_clone';
module.exports = { host, user, password, database };

错误本身就是你的conn变量没有值,原因可以有多种。看看这一行

      const conn = await connection(dbConfig).catch(e => {});

首先,您有 catch 块并且您没有处理错误,因此如果发生错误,您将不会得到任何响应,请确保正确处理每个错误。

并确保 connection 按预期 return 连接对象,而不是 return 未定义或其他情况。