TypeError :req.gravatar 不是函数

TypeError :req.gravatar is not a function

提问人:techy studio 提问时间:7/13/2020 更新时间:7/13/2020 访问量:156

问:

我创建了一个电子商务应用程序,在其中我遇到了一些关于req.gravatar()不是函数的问题。

每当我通过邮递员发送数据时,都会给我错误,这些错误是我在上面定义的。

帐户.js文件代码

const router = require('express').Router();
const jwt = require('jsonwebtoken');

const User = require('../models/user');
const config = require('../config');
var gravatar = require('gravatar');

router.post('/signup', (req, res, next) => {
    let user = new User();
    user.name = req.body.name;
    user.email = req.body.email;
    user.password = req.body.password;
    user.picture = req.gravatar();
    user.isSeller = req.body.isSeller;

User.findOne({ email: req.body.email }, (err, existingUser) => {
    if(existingUser) { 
        res.json({
            success: false,
            message: 'Account with that email is already exist'
        });
    }
    else{
        user.save();
        
        var token = jwt.sign({
            user: user
        }, config.secret, {
            expiresIn: '7d'
        });

        res.json({
            success: true,
            message: 'Enjoy your token',
            token: token
        });
    }
});
});

module.exports = router;

用户 .js 文件代码

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const bcrypt = require('bcrypt-nodejs');
const crypto = require('crypto');


const UserSchema = new Schema({
    email: { type: String, unique: true, lowercase: true },
    name: String,
    password: String,
    picture: String,
    isSeller: { type: Boolean, default: false },
    address: {
        add1: String,
        add2: String,
        city: String,
        state: String,
        country: String,
        postalCode: String
    },
    created: { type: Date, default: Date.now }
});

UserSchema.pre('save', function(next) {
    var user = this;

    if(!user.isModified('password')) return next();

    bcrypt.hash(user.password, null, null, function(err, hash) {
        if(err) return next(err);

        user.password = hash;
        next();
    });
});

UserSchema.methods.comparePassword = function(password) {
    return bcrypt.compareSync(password, this.password);
}

UserSchema.methods.gravatar = function(size) {
    if(!this.size) size = 200;
    if(!this.email) {
        return 'https://gravatar.com/avatar/?s' + size + '&d=retro';
    }
    else{
        var md5 = crypto.createHash('md5').update(this.email).digest('hex');
        return 'https://gravatar.com/avatar/' + md5  + '?s' + size + '&d=retro';
    }
}

module.exports = mongoose.model('User', UserSchema);

请帮我尽快解决这个问题。 因为我是 node.js 技术的业余开发人员。

JavaScript 节点.js gravatar

评论


答:

0赞 Luciano Mammino 7/13/2020 #1

在下一行中,不是 的属性,因此不能作为函数调用gravatarreq

user.picture = req.gravatar();

我想你想做的,是这样的:

user.picture = gravatar.url(user.email);

进行此更改后,将包含该电子邮件的 gravatar 用户个人资料图片的 URL。user.picture

评论

0赞 Luciano Mammino 7/14/2020
很高兴听到,享受:)