开发者问题收集

Nodejs - UnhandledPromiseRejectionWarning:TypeError:无法将未定义或空转换为对象

2019-11-28
3415

我有以下内容

SessionController.js

import User from '../models/User';

class SessionController {
   async store(req, res) {
      const { email, password } = req.body;

      console.log(req.body);

      const user = await User.findOne({ where: { email } });
   }
}

export default new SessionController();
import Sequelize, { Model } from 'sequelize';
import bcrypt from 'bcryptjs';

class User extends Model {
   static init(sequelize) {
      super.init(
         {
            name: Sequelize.STRING,
            email: Sequelize.STRING,
            password_hash: Sequelize.STRING,
         },
         {
            sequelize,
         }
      );

      return this;
   }

   checkPassword(password) {
      return bcrypt.compare(password, this.password_hash);
   }
}

export default User;

以及 Insomnia 从 /sessions 路由发送数据 enter image description here

我调用 console.log(req.body) 并获取所有数据,所以我不知道为什么会出现此错误:

(node:8589) UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at Function.findAll (/home/julio/www/bootcamp2019/gympoint/node_modules/sequelize/lib/model.js:1692:47)
    at Function.findOne (/home/julio/www/bootcamp2019/gympoint/node_modules/sequelize/lib/model.js:1924:17)
    at store (/home/julio/www/bootcamp2019/gympoint/src/app/controllers/SessionController.js:10:41)......

有什么想法吗?

2个回答

我也遇到了同样的问题。

我发现我的数据库路径是错误的,您可以在第 4 行和第 5 行看到。

import express from 'express';
import routes from './routes';

// import './config/database'; (Wrong)
import './database'; // (Correct)

class App {
  constructor() {
    this.server = express();

    this.middlewares();
    this.routes();
  }

  middlewares() {
    this.server.use(express.json());
  }

  routes() {
    this.server.use(routes);
  }
}

export default new App().server;
Beto Doescher
2020-03-24

将异步函数的 await 调用放在 try/catch 块中。

import User from '../models/User';

class SessionController {
    async store(req, res) {
        try {
            const { email, password } = req.body;

            console.log(req.body);

            const user = await User.findOne({ where: { email } });
        } catch (e) {
            console.log("Error Occurred", e)
        }

    }
}

export default new SessionController();
Vipulw
2019-11-28