【问题标题】:Express js - how to remove certain field from responseExpress js - 如何从响应中删除某些字段
【发布时间】:2021-09-06 18:29:48
【问题描述】:

在我当前的登录 api 中,它返回

"user": {
        "id": "3e85decc-2af4-436c-8b7f-e276771234f5",
        "email": "cccc@cccc.com",
        "password": "$xxxxxxxxxx",
        "createdAt": "2021-05-14T08:48:31.000Z",
        "updatedAt": "2021-05-14T08:48:31.000Z"
    },
    "token": "xxxxx"
}

我想删除回复中的 password 字段,因此我在代码中使用了 delete user.password,但它不起作用

/api/users.js

router.post('/login', (req, res, next) => {
  passport.authenticate('local', {session: false}, (err, user, info) =>{
    if (err || !user) {...}
    req.login(user, {session: false}, (err) => {
      if (err) {
          res.send(err);
      }
      const token = jwt.sign(user, 'your_jwt_secret');
      console.log(user) // show dataValues and _previousDataValues instead of normal JSON object
      delete user.password // not working
      return res.json({user, token});
   });
  })(req, res);
});

我尝试为上述文件记录user 对象,它返回:

users {

dataValues: {

id: '3e85decc-2af4-436c-8b7f-e276771234f5',

email: 'cccc@cccc.com',

password: '$xxxxxxxxxx',

createdAt: 2021-05-14T08:48:31.000Z,

updatedAt: 2021-05-14T08:48:31.000Z

},

_previousDataValues: {

id: '3e85decc-2af4-436c-8b7f-e276771234f5',

email: 'cccc@cccc.com',

password: '$xxxxxxxxxx',

createdAt: 2021-05-14T08:48:31.000Z,

updatedAt: 2021-05-14T08:48:31.000Z

},

_changed: Set(0) {},

_options: {

isNewRecord: false,

_schema: null,

_schemaDelimiter: '',

raw: true,

attributes: [ 'id', 'email', 'password', 'createdAt', 'updatedAt' ]

},

isNewRecord: false

}

这是我的用户模型。我正在使用 Sequelize。

const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
const db = require('../sequelize')

let users = db.define('users', {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      allowNull: false,
      primaryKey: true
    },
    email: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: 'email'
    },
    password: {
      type: DataTypes.STRING,
    },
  },
  {
    hooks: {
      beforeCount(options) {
        options.raw = false;
      }
    }
  }
);
  
module.exports = users;

【问题讨论】:

    标签: mysql node.js express sequelize.js


    【解决方案1】:

    直接从模型中删除属性可能不是一个好主意。尝试使用ToJSON() 将模型转换为纯 Javascript 对象并从中删除密码。

    plainUser = user.ToJSON();
    delete plainUser.password
    

    【讨论】:

    • user.ToJSON 不是函数
    【解决方案2】:

    为什么不重新创建结果响应,如下所示:

    let response = {
         "user": {
             "id": user.dataValues.id,
             "email": user.dataValues.email,
             "createdAt": user.dataValues.createdAt,
             "updatedAt": user.dataValues.updatedAt
         },
         "token": "xxxxx"
     }
    JSON.stringify(response)
    

    【讨论】:

      【解决方案3】:

      在您的模型中尝试以下代码来覆盖 sequelize toJSON 函数

      const User = db.define('users', {
          id: {
              type: DataTypes.UUID,
              defaultValue: DataTypes.UUIDV4,
              allowNull: false,
              primaryKey: true
          },
          email: {
              type: DataTypes.STRING,
              allowNull: false,
              unique: 'email'
          },
          password: {
              type: DataTypes.STRING,
          },
      },
          {
              hooks: {
                  beforeCount(options) {
                      options.raw = false;
                  }
              }
          }
      );
      
      User.prototype.toJSON = function () {
       const values = Object.assign({}, this.get());
      
       delete values.password;
       return values;
      };
      

      或使用omit()lodash 以获得更简洁的代码

      User.prototype.toJSON = function () {
      const values = {
          ..._.omit(this.get(), ['password'])
      };
      
      return values;
      };
      

      【讨论】:

        【解决方案4】:

        终于用user.get({plain: true})解决了

              let plainUser = user.get({plain: true})
              delete plainUser['password']
              return res.json({user, token});
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-02
          • 2018-07-29
          • 1970-01-01
          相关资源
          最近更新 更多