Nodejs - UnhandledPromiseRejectionWarning:

我有以下


会话控制器.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();


用户.js


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 路由发送数据

http://img.mukewang.com/61e01428000169e707640736.jpg

我打电话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)......

任何的想法?


aluckdog
浏览 477回答 2
2回答

蓝山帝景

同样的问题也发生在我身上。我发现我在第 4 行和第 5 行看到了错误的数据库路径。import express from 'express';import routes from './routes';// import './config/database'; (Wrong)import './database'; // (Correct)class App {&nbsp; constructor() {&nbsp; &nbsp; this.server = express();&nbsp; &nbsp; this.middlewares();&nbsp; &nbsp; this.routes();&nbsp; }&nbsp; middlewares() {&nbsp; &nbsp; this.server.use(express.json());&nbsp; }&nbsp; routes() {&nbsp; &nbsp; this.server.use(routes);&nbsp; }}export default new App().server;

侃侃尔雅

将 async 函数的 await 调用放在 try/catch 块中。import User from '../models/User';class SessionController {&nbsp; &nbsp; async store(req, res) {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const { email, password } = req.body;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(req.body);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const user = await User.findOne({ where: { email } });&nbsp; &nbsp; &nbsp; &nbsp; } catch (e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("Error Occurred", e)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}export default new SessionController();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript