错误:参数非法:未定义,字符串

时间:2018-10-01 07:20:39

标签: javascript node.js express postman bcrypt

我一直在MERN项目上与Bcrypt纠缠不清,我试图在Postman上运行测试(注册过程),但是每次尝试都会出现此错误:错误:非法参数:undefined,字符串在此行:

if (err) throw err;

这是我的服务器主配置文件:

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const users = require('./routes/api/users');
const profile = require('./routes/api/profile');
const posts = require('./routes/api/posts');

const app = express();

// Body parser Middleware
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(bodyParser.json());

// MongoDB Config
const db = require('./config/keys').mongoURI;

// MongoDB Connection
mongoose
  .connect(db)
  .then(() => console.log('MongoDB Connected'))
  .catch(err => console.log(err));

app.get('/', (req, res) => res.send('Hello!'));

const port = process.env.PORT || 3000;

app.listen(port, () => console.log(`Server Runing on port ${port}`));

// Using Routes

app.use('/api/users', users);
app.use('/api/profile', profile);
app.use('/api/posts', posts);

这是我收到错误的用户配置文件:

const express = require('express');
const router = express.Router();
const gravatar = require('gravatar');
const bcrypt = require('bcryptjs');

// Load user model:
const User = require('../../models/User');

router.get('/test', (req, res) => res.json({ msg: "Users Works" }));

router.post('/register', (req, res) => {
  User.findOne({ email: req.body.email })
    .then(user => {
      if (user) {
        return res.status(400).json({ email: "Email already exists" });
      } else {
        const avatar = gravatar.url((req.body.email, {
          s: '200', // Size
          r: 'pg', // Rating
          d: 'mm'  // Default image
        }));

        const newUser = new User({
          name: req.body.name,
          email: req.body.email,
          avatar,
          password: req.body.password
        });
        bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) throw err;
            newUser.password = hash;
            newUser.save()
              .then(user => res.json(user))
              .catch(err => console.log(err));
          })
        })
      }
    })
})


module.exports = router;

这是我在邮递员上看到的:

enter image description here

我一直在审查它,似乎没有任何错误,而且我真的不明白为什么告诉我“未定义的字符串”。如果您发现我没有注意到的任何错误,我们将非常感谢您的反馈,谢谢!

1 个答案:

答案 0 :(得分:1)

   const newUser = new User({
      name: req.body.name,
      email: req.body.email,
      avatar,  <------------------------- avatar:'', or avatar:null,
      password: req.body.password
    });