语法错误:JSON中的意外令牌}

时间:2018-12-24 12:22:08

标签: javascript node.js express jwt passport.js

  

我正在尝试使用通行证js创建注册路线。上   使用邮递员的请求,我收到此错误:SyntaxError:   JSON中的意外令牌}在位置119
处   JSON.parse(

     

下面是我的代码:

const express = require("express");
const router = express.Router();
const gravatar = require("gravatar");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const keys = require("../config/keys");
const passport = require("passport");
//load input validation
const validateRegisterInput = require("../validation/register");
//user model
const User = require("../models/User");

router.get("/test", (req, res) => res.json({ msg: "user route works" }));

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

      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        password: req.body.password,
        avatar
      });


      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;
  

以下是我使用邮递员的请求:

{
  "name":"Harry",
  "email": "harrypotter@gmail.com",
  "password" : "harry",
  "avatar" : "https://image.jpg",
}

1 个答案:

答案 0 :(得分:1)

根据您的代码,您需要在体内发送password2。因此,请使用下面的curl进行请求,您会没事的。

  

卷曲-X POST \ http://localhost:8080/api/users/register \ -H   '缓存控制:无缓存'\ -H'内容类型:application / json'\
  -H'邮递员令牌:c437c084-def1-427f-bf43-33b92a747244'\ -d'{“ name”:“ Harry”,“ email”:“ harrypotter@gmail.com”,“ password”:   “ harry12”,“ password2”:“ harry12”,“ avatar”:“ https://image.jpg”   }'