简体   繁体   English

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

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

I am having issues with fetching from my api, and I keep getting the aforementioned error and have no clue what is going wrong.我在从我的 api 获取时遇到问题,并且我不断收到上述错误,并且不知道出了什么问题。 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:这是我们在 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;

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.它需要唯一的电子邮件,并且来自过去注册测试的现有电子邮件导致后端行为不可预测。

暂无
暂无

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

相关问题 未处理的拒绝 (SyntaxError):JSON 输入的意外结束,带有获取请求 - Unhandled Rejection (SyntaxError): Unexpected end of JSON input with Get request fetch SyntaxError:JSON解析错误:意外的标识符“object” - SyntaxError: JSON Parse error: Unexpected identifier “object” SyntaxError:JSON解析错误:意外的标识符“功能” - SyntaxError: JSON Parse error: Unexpected identifier “function” × 未处理的拒绝(SyntaxError):JSON 输入意外结束 - × Unhandled Rejection (SyntaxError): Unexpected end of JSON input JSON 解析错误:针对获取 API 请求的意外标识符“数组” - JSON Parse error: Unexpected identifier "Array" against Fetch API request 无法获取 api -“未处理的 promise 拒绝” - Cannot fetch api - "Unhandled promise rejection" React App无法解析获取路由:未处理的拒绝(SyntaxError):JSON中位置0处的意外令牌&lt; - React App not resolving fetch route: Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0 SyntaxError:JSON解析错误:意外的标识符“对象”(匿名函数) - SyntaxError: JSON Parse error: Unexpected identifier “object” (anonymous function) 未处理的拒绝(SyntaxError):JSON中位置0上的意外令牌&lt;React - Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0 React 获取“未处理的拒绝(SyntaxError):JSON 输入的意外结束” - Getting “Unhandled Rejection (SyntaxError): Unexpected end of JSON input”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM