向服务器发送请求时出现 Json 语法错误

时间:2021-07-27 15:30:31

标签: node.js json api fetch-api

当我尝试对用户进行身份验证时,如果用户已登录或完全授权访问该特定页面,则该用户只能访问关于页面,我收到了 Json 解析错误,在服务器端我也是没有得到饼干。
客户端关于

const callAboutPage = async () => {
        try{
            const res = await fetch("http://localhost:8000/about", {
                method: "GET",
                headers:{
                    Accept: "application/json",
                    "Content-Type": "application/json"
                },
                credentials: "include"
            });

            const data = await res.json();
            console.log(data)
            if(!res.status === 200){
                console.log("Im here");
                const error = new Error(res.error);
                throw error;
            }
            if(res.status === 200){
                console.log("You're right")
            }
        }
        catch(err){
            console.log("Error: ",err);
            history.push("/login")
        }
    }

控制台错误

Error:  SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

它正在向服务器端发出请求,但在服务器端我也收到错误

服务器端

router.get("/about",authenticate,  (req, res) =>{
  console.log("Hello world!");
  res.send(req.rootUser);
  
})

const Authenticate = async (req, res, next) => {
    try{
            const token = req.cookies.jwtoken;
            const verifyToken = jwt.verify(token, process.env.SECRET_KEY);

            const rootUser = await User.findOne({_id:verifyToken._id, "tokens.token":token});
            if(!rootUser) {throw new Error("User not Found")}

            req.token = token;
            req.rootUser = rootUser;
            req.UserId = rootUser._id;
            next();
    }
    catch(err){
        res.status(401).send("Unauthorized: No token provided");
        console.log(err);
    }
}

错误

TypeError: Cannot read property
'jwtoken' of undefined
    at Authenticate (D:\MERN\server\middleware\authenticate.js:6:39)
    at Layer.handle [as handle_request] (D:\MERN\server\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\MERN\server\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\MERN\server\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (D:\MERN\server\node_modules\express\lib\router\layer.js:95:5)
    at D:\MERN\server\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (D:\MERN\server\node_modules\express\lib\router\index.js:335:12)
    at next (D:\MERN\server\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (D:\MERN\server\node_modules\express\lib\router\index.js:174:3)
    at router (D:\MERN\server\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (D:\MERN\server\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (D:\MERN\server\node_modules\express\lib\router\index.js:317:13)
    at D:\MERN\server\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (D:\MERN\server\node_modules\express\lib\router\index.js:335:12)
    at next (D:\MERN\server\node_modules\express\lib\router\index.js:275:10)
    at cors (D:\MERN\server\node_modules\cors\lib\index.js:188:7)

Cookie 将在登录时添加
登录

router.post("/login", async (req, res) => {
  try {
    const { email, password } = req.body;
    if (!email || !password) {
      return res.status(422).json({ error: "pls filled all the field" });
    }

    const userLogin = await User.findOne({
      $and: [{ email: email }],
    });
    if (!userLogin) {
      return res.status(422).json({ error: "User is not authorized" });
    }
    if (userLogin) {
      const passwordMatch = await bcrypt.compare(password, userLogin.password);
      const token =  await userLogin.generateAuthToken();
      
      res.cookie('jwtoken', token, {
          expires: new Date(Date.now() + 25892000000),
          httpOnly:true
      })
      if (passwordMatch) {
        res.status = 200;
        return res.json({ message: "login success" });
      } else {
        return res.status(400).send({ error: "The password is invalid" });
      }
    }
  } catch (err) {
    console.log(`Error: ${err}`);
  }
});

1 个答案:

答案 0 :(得分:-1)

您的服务器以 401 未授权响应和正文“未授权:未提供令牌”作为响应。

在您的客户端上,您使用 const data = await res.json(); 解码服务器响应,这会导致 JSON 语法错误,因为“未授权:未提供令牌”不是有效的 json 格式。您应该首先检查响应状态,然后使用 res.json() 解码您的响应正文。

关于 cookie 问题,我没有看到设置或发送 cookie 的代码。