【问题标题】:Cannot set property statusCode of undefined [closed]无法设置未定义的属性 statusCode [关闭]
【发布时间】:2020-01-29 10:24:06
【问题描述】:

我正在尝试为我的应用程序创建一个后端,实际上我正在为用户编写路由登录,但是当我使用 Postman 测试路由时遇到错误,此错误是:

UnhandledPromiseRejectionWarning:TypeError:无法设置属性 'statusCode' 未定义

在线上

this.response.statusCode = 401

这是我的代码:

import Rider from '../../models/riders'
import jwt from 'jsonwebtoken'

export default class LoginService {
/**
 * @param {String} email
 * @param {String} password 
 * */
constructor(email, password) {
    this.email = email
    this.password = password

    this.reponse = {
        statusCode: 200,
        responseData: {},
    }
}

loginRider() {
    return new Promise((resolve) => {
        this.checkIdentifiant()
          .then((r) => {
            // identifiant correct, l'user peut se connecter
            console.log(r)
            console.log("apres then apres checkidentifiant")
            this.response.responseData = {
              token: jwt.sign(r.toJSON(), process.env.TOKEN_PASSWORD),
            }
            resolve(this.response)
          })
          .catch((e) => {
            console.log("dans le catch login rider")
            console.log(e)
            // erreur lors de l'authentification / error code unauthorized 401
            this.response.statusCode = 401
            this.response.responseData = {
              error: 'unauthorized',
              error_description: 'Identifiants incorrect',
            }

            // On log l'erreur dans la console pour l'admin
            resolve(this.response)
          })
      })
}

/**
* Vérifie le mot de passe et l'email de l'user qui tente de se connecter
*
* @returns {boolean}
*/
checkIdentifiant() {
// on cherche un livreur ayant le même mail que celui fourni dans la BDD
return new Promise((resolve, reject) => {
  Rider.findOne({ email: this.email, password: this.password }, (err, rider) => {
    if (err || !rider) {
      console.log("identifiant invalide dans le checkidentifiant")
      reject()
    }
    // si le rider est trouvé dans la BDD
    if (rider) {
      console.log("identifiant correct, dans le check identifiant")
      // pas sécurisé, à améliorer
      resolve(rider)
    }
  })
})
}
}

我放的console.log显示我在LoginRider的block catch中运行。

我使用 nodeJS 和 expressJS 来编写我的后端,我的数据库使用 MongoDB。 Postman 用于测试 API

【问题讨论】:

  • this.response 似乎未定义。您的路线在哪里定义?应该有引用(req, res)

标签: javascript node.js mongodb api express


【解决方案1】:

this.response 的第一个声明有错别字

  this.reponse   => this.response

【讨论】:

  • 谢谢,就是这样……对不起。
  • @Pixelyoda,如果只是这样,你可以接受我的回答
  • 是的,谢谢,但现在很奇怪,checkIdentifiant 中的 findOne 方法为骑手返回了一个空对象,但我的数据库已经在本地环境中运行,并且模式骑手和数据存在......跨度>
猜你喜欢
  • 1970-01-01
  • 2021-02-04
  • 2021-11-27
  • 2022-10-30
  • 2023-02-10
  • 1970-01-01
  • 2015-12-07
  • 2013-05-28
相关资源
最近更新 更多