API Fetch Issue: Unhandled promise rejection: SyntaxError: JSON Parse error: Unexpected identifier "Server"

Viewed 514

I am having issues with fetching from my api, and I keep getting the aforementioned error and have no clue what is going wrong. Essentially what I'm trying to do is create a user, then get the token returned to me to create another profile.

I'm not completely sure whether it's an issue with the front end or back end, and don't know how to determine if it is one or the other. Here's the code in the front end:

        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))

Any help would be much appreciated. Thanks.

EDIT

This is the our route on our api that is called for registering a user:

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;
1 Answers

Turns out the issue was with the backend. It required unique emails, and existing emails from past registration testing was causing the back end to act unpredictably.

Related