javascript - 使用 node express 应用程序注册帐户继续在 postman 中加载

标签 javascript node.js express

我正在使用 nodejs 并为用户创建了一个注册模型,但在 postman 中运行后,没有响应或失败。我只是被困在那里并在我的终端中得到以下响应

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:12675) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code

下面是我的模型代码

const AccountSchema = new mongoose.Schema(
    {
        fullName: {
            type: String,
            require: true,
            minlength: 2
        },
        email: {
            type: String,
            required: true,
            trim: true,
            minlength: 1,
            unique: true,
            validate: {
                validator: validator.isEmail,
                message: '{VALUE} is not a valid email'
            }
        },
        password: {
            type: String,
            require: true,
            minlength: 6
        },

        token: {
            type: String,
            required: true
        },
        timestamp: {
            type: Date,
            default: Date.now
        }

    }
);

AccountSchema.methods.toJSON = function () {
    const user = this
    const userObject = user.toObject()

    return _.pick(userObject, ['_id','fullName', 'email', 'token'])
}

AccountSchema.methods.generateAuthToken = function () {
    let user = this
    const today = new Date();
    const expirationDate = new Date(today);
    expirationDate.setDate(today.getDate() + 60);
    const token = jwt.sign({
        email: user.email,
        _id: user._id.toHexString(),
        exp: parseInt(expirationDate.getTime() / 1000, 10),
    }, 'process.env.JWT_SECRET').toString()

    user.token.push({
        token
    })

    return user.save().then(() => {
        return token
    })
}

AccountSchema.pre('save', function (next) {
    let user = this

    if (user.isModified('password')) {
        bcrypt.genSalt(10, (err, salt) => {
            bcrypt.hash(user.password, salt, (err, hash) => {
                user.password = hash
                next()
            })
        })
    } else {
        next()
    }
})

const Account = mongoose.model('Account', AccountSchema)

在我的 Controller 中,我有这个

缺点

t _ = require('lodash')
const {Account} = require('../models/account')

exports.register = (req, res, next) => {
    const body = _.pick(req.body, ['fullName', 'email', 'password'])
    console.log(body)
    const account = new Account(body)
    account.save().then(() => {
        return account.generateAuthToken()
    }).then((token) => {
        res.header('Authorization', token).send(account)
    }).catch((e) => {
        res.status(400).send(err)
    })
}

那我的 postman 是这样的

{
    "fullName": "Adie Olami",
    "email": "ugbe@gmail",
    "password": "123456"
}

我还要补充一点,我是 node 的新手,仍在学习中,因此非常感谢您的帮助

最佳答案

使用 async/await 的非常简单的解决方案:

t _ = require('lodash')
const {Account} = require('../models/account')

exports.register = async (req, res, next) => {
    const body = _.pick(req.body, ['fullName', 'email', 'password'])
    console.log(body)
    const account = new Account(body)
try {
    await account.save();
    const accessToken = await account.generateAuthToken()
    res.header('Authorization', token).send(account)
 } catch(err) {
    res.status(400).send(err)
 }
}

关于javascript - 使用 node express 应用程序注册帐户继续在 postman 中加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55935612/

相关文章:

javascript - 如何使用 Puppeteer 或 Chrome 控制台以编程方式切换 JS 上下文(到不同域的 iframe 上下文)

javascript - 有没有办法改变整个网页客户端的色调?

javascript - Node.js/Express 视频流(HTTP 206 部分内容)

javascript - Nodejs 和 Express 服务器在 2 分钟后关闭连接

javascript - 在 three.js 中从场景中完全移除网格的正确方法是什么?

javascript - HTML5 Canvas Tileset 绘图

javascript - 即使在 return 语句之后代码仍在执行吗?

node.js - Nodejs 需要查看哪个客户端已退出

javascript - 从 Angular 服务访问第 3 方 JS 函数

c++ - 使用 Microsoft Visual C++ 2010 Express 时出现链接错误 LNK1123