Express js - 如何从响应中删除某些字段

时间:2021-06-23 07:55:47

标签: mysql node.js express sequelize.js

在我当前的登录 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;

4 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

尝试在您的模型中使用以下代码覆盖 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;
};

答案 3 :(得分:0)

最后用user.get({plain: true})

解决了
      let plainUser = user.get({plain: true})
      delete plainUser['password']
      return res.json({user, token});
相关问题