繁体   English   中英

API 获取问题:未处理的承诺拒绝:语法错误:JSON 解析错误:意外的标识符“服务器”

[英]API Fetch Issue: Unhandled promise rejection: SyntaxError: JSON Parse error: Unexpected identifier “Server”

我在从我的 api 获取时遇到问题,并且我不断收到上述错误,并且不知道出了什么问题。 基本上我要做的是创建一个用户,然后将令牌返回给我以创建另一个配置文件。

我不完全确定这是前端还是后端的问题,也不知道如何确定是其中之一。 这是前端的代码:

        let response;

        await fetch('https://herokuapiurl.com/api/users', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                'name': name,
                'email': email,
                'password': password,
                'phoneNumber': phoneNumber,
                'userName': userName,
                'address': address
            })
        })
            .then(msg => {
                response = msg.json()
                return response
            })
            .then(msg => console.log(JSON.stringify(msg) + ' This is part of the .then()'))
        fetch('https://apiurl.com/api/profiles', {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'x-auth-token': response
            },
            body: JSON.stringify({
                'name': name,
                'email': email,
                'password': password,
                'phoneNumber': phoneNumber,
                'userName': userName,
                'address': address
            })
        }
        )
            .then(msg => msg.json())
            .then(msgJSON => console.log(msgJSON + ' this fired'))
            .catch((error) => console.log(error))

任何帮助将非常感激。 谢谢。

编辑

这是我们在 api 上的用于注册用户的路由:

router.post(
  "/",
  [
    check("name", "name is required").not().isEmpty(),
    check("email", "Please inclue a valid email").isEmail(),
    check(
      "password",
      "Please enter a password with 6 or more characters"
    ).isLength({ min: 1 }),
    check("phoneNumber", "Phone Number is required").isMobilePhone(),
    check("address", "address is required").not().isEmpty(),
    check("userName", "Username is required").not().isEmpty(),
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { name, email, password, phoneNumber, userName, address } = req.body;
    try {
      let user = await User.findOne({ userName });
      if (user) {
        return res
          .status(400)
          .json({ errors: [{ msg: "User already exists" }] });
      }
      console.log(userName);
      //get users gravitar
      const avatar = gravatar.url(email, {
        s: "200",
        r: "pg",
        d: "mm",
      });

      user = new User({
        name,
        email,
        password,
        phoneNumber,
        userName,
        address,
        gravatar: avatar,
      });

      const salt = await bcrypt.genSalt(10);

      user.password = await bcrypt.hash(password, salt);

      await user.save();

      const payload = {
        user: {
          id: user.id,
        },
      };

      jwt.sign(
        payload,
        config.get("jwtSecret"),
        { expiresIn: 360000 },
        (err, token) => {
          if (err) throw err;
          res.json({ token });
        }
      );
      console.log(userName);
      //res.send("User registered");
    } catch (err) {
      console.error(err.message);
      res.status(500).send("Server Error");
    }
  }
);

module.exports = router;

原来问题出在后端。 它需要唯一的电子邮件,并且来自过去注册测试的现有电子邮件导致后端行为不可预测。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM