意味着堆栈错误“意外的令牌#json在位置0”

时间:2018-05-04 12:21:08

标签: node.js angular express

我想通过从网址中获取此人的姓名,将{follow}功能添加到我的应用中。

但是我收到了这个错误:

  

SyntaxError:位于0的JSON中的意外标记#       在JSON.parse()
      at createStrictSyntaxError(C:\ Users \ hathefa \ Desktop \ prozad \ node_modules \ body-parser \ lib \ types \ json.js:157:10)
      在解析时(C:\ Users \ hathefa \ Desktop \ prozad \ node_modules \ body-parser \ lib \ types \ json.js:83:15)
      在C:\ Users \ hathefa \ Desktop \ prozad \ node_modules \ body-parser \ lib \ read.js:121:18
      在invokeCallback(C:\ Users \ hathefa \ Desktop \ prozad \ node_modules \ raw-body \ index.js:224:16)
      完成后(C:\ Users \ hathefa \ Desktop \ prozad \ node_modules \ raw-body \ index.js:213:7)
      在IncomingMessage.onEnd(C:\ Users \ hathefa \ Desktop \ prozad \ node_modules \ raw-body \ index.js:273:7)
      在IncomingMessage.emit(events.js:160:13)
      at endReadableNT(_stream_readable.js:1101:12)
      at process._tickCallback(internal / process / next_tick.js:152:19)

我不知道问题是什么。

这是HTML代码:

<form  class="btn btn-info btn-lg btn-block" (submit)="follow()">

                              <button type="submit" class="btn btn-info btn-lg btn-block"  [disabled]="FlowwersBy.indexOf(myUsername) > -1"> Follow</button>
                            </form>

这是Angular代码:

follow(){
    this.authService.follow(this.username).subscribe(data =>{
      if(!data.success){
        this.messageClass = 'alert alert-danger'; // Set bootstrap error class
        this.message = data.message; // Set error message
        console.log('no');
      }else{
        this.messageClass = 'alert alert-success'; // Set bootstrap error class
        this.message = data.message; // Set error message
        console.log('yes');

      }
    });
  }

这是服务代码:

follow(user){
  this.createAuthenticationHeaders(); // Create headers before sending to API
  return this.http.put(this.domain + '/authentication/follow/',user, this.options).map(res => res.json());
}

这是节点代码:

router.put('/follow',(req,res)=>{
    if(!req.body.username){
      res.json({success:false,message:'user not provided'});
      console.log(req.body.username);
    }else{
      User.findOne({username:req.body.username},(err,user)=>{
        if(!user){
          res.json({success:false,message:'user not found'});
        }else{
          if(!req.body.follower){
            res.json({success:false , message:'no follower provided'});
          }else{
            User.findOne({username:req.decoded.username},(err,follow)=>{
              if(!follow){
                res.json({success:false,message:'no follower was provided'});
              }else{
                if(user.FlowwersBy.includes(follow.username)){
                  res.json({success:false , message:"you alraedy follow him"});
                }else{

                  User.findByIdAndUpdate(user._id,
                  {
                    $push:{FlowwersBy:follow.username},
                    $inc:{Flowwers:1}
                  },
                  {
                    new: true
                  },
                  function(err,user){
                    if(err){
                      res.json({success:false, message:err});
                    }else{
                      //
                        User.findByIdAndUpdate(follow._id,
                        {
                          $push:{FlowwingBy:user.username},
                          $inc:{Flowwing:1}
                        },
                        {
                          new: true
                        },
                        function(err,follower){
                          if(err){
                            res.json({success:false, message:err});
                          }else{

                            res.json({success:true, message:'done'});
                            //res.json({user});
                          }
                        }
                      )
                      //
                    }
                  }
                )

                }
              }
            });
          }
        }
      });
    }
  });

这是授权码:

/ * ============================================= ===   MIDDLEWARE - 用于从标头中获取用户的令牌   ================================================ * /

 router.use((req, res, next) => {
    const token = req.headers['authorization']; // Create token found in headers
    // Check if token was found in headers
    if (!token) {
      res.json({ success: false, message: 'No token provided' });  // Return error
    } else {
      // Verify the token is valid
      jwt.verify(token, config.secret, (err, decoded) => {
        // Check if error is expired or invalid
        if (err) {
          res.json({ success: false, message: 'Token invalid: ' + err }); // Return error for token validation
        } else {
          req.decoded = decoded; // Create global variable to use in any request beyond
          next(); // Exit middleware
        }
      });
    }
  });

当我用邮递员测试后端时,它可以正常工作。

当我打开开发工具网络选项卡时。 这是标题:

General:
Request URL: http://localhost:8080/authentication/follow/
Request Method: PUT
Status Code: 400 Bad Request
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade
Response Headers:
Access-Control-Allow-Origin: http://localhost:4200
Connection: keep-alive
Content-Length: 1085
Content-Security-Policy: default-src 'self'
Content-Type: text/html; charset=utf-8
Date: Sat, 05 May 2018 06:11:42 GMT
Vary: Origin
X-Content-Type-Options: nosniff
X-Powered-By: Express
Request Headers:
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ar,en-US;q=0.9,en;q=0.8,fr;q=0.7
authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1YWVjMWYwMzE2NDEwMzI3YmNkMmRiYmQiLCJpYXQiOjE1MjU1MDA0MjYsImV4cCI6MTUyNTU4NjgyNn0.ivwk4xWUJLNsYjx2lcV4U7JMO1Z8HOV-m-yNizIxiDk
Connection: keep-alive
Content-Length: 4
Content-Type: application/json
Host: localhost:8080
Origin: http://localhost:4200
Referer: http://localhost:4200/user/meme
User-Agent: Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36
Request Payload:
meme

这是网址:

http://localhost:4200/user/meme

我解决了错误问题是我发送到后端的变量不是json类型,我在Chrome中使用了网络开发工具后想出来,感谢“Kalamarico”的建议。< / p>

这是固定代码:

follow(username){
  this.createAuthenticationHeaders(); // Create headers before sending to API
  return this.http.put(this.domain + '/authentication/follow/',JSON.stringify({username}), this.options).map(res => res.json());
}

我所做的只是将变量转换为json对象。

希望你能从我的错误中吸取教训。

0 个答案:

没有答案