什么是请求有效负载,为什么它会捕获我发送的数据。

时间:2018-01-30 11:21:32

标签: node.js angular rest express

使用Angular作为前端层和后端节点开发单页应用程序,而用户日志提交它在Request Payload中捕获用户名和密码。 我不知道这个,为什么它捕获以及如何限制它。 以下是有效载荷数据的示例。

Valid XHTML

HTML:

<form [formGroup]="loginform" (ngSubmit)="login()">
<div class="form-group">
<label for="name">User name</label>
<input type="text" class="form-control" name="name" formControlName="name" placeholder="User Name">
</div>
<div class="form-group">
<label for="name">password</label>
<input type="password" class="form-control" name="password" formControlName="password" placeholder="password">
</div>
<input type="checkbox" value="1" formControlName="validate"/>
<button type="submit" [disabled]="!loginform.valid" class="btn">
login</button>
</form>

登录-component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AuthGuard } from '../../guards/auth.guard';
import { Router } from '@angular/router';
import { DataService } from '../../data-service';

@Component({
  selector: 'login-page',
  templateUrl: './login-page.html',
  styleUrls: [ './login-page.css' ]
})
export class LoginPage implements OnInit {
  loginform: FormGroup;
  previousUrl;

  constructor(private fb: FormBuilder, private service: DataService, private authGuard: AuthGuard,
  private router: Router){
    this.loginform = this.fb.group({
     'name': [null, Validators.required],
     'password': ['', Validators.required],
     'validate' : ''
      });
  }

 ngOnInit()  { }
 login(){
    const user = {
      "email" : this.loginform.get('name').value,
      "password" : this.loginform.get('password').value
    }
   this.service.login(user)
   .subscribe((data) => {
     if (!data.success) {
       this.messageClass = 'alert alert-danger';
     }
     else {
       this.messageClass = 'alert alert-success';
       this.service.storeUserData(data.token, data.user, data.admin);
       setTimeout(() => {
          console.log('Success');
          if (this.previousUrl) {
            this.router.navigate([this.previousUrl]);
          } else {
            this.router.navigate(['/dashboard']);
          }
        }, 1000)
     }
   })
  }
}

service.ts

login(user){
    return this.http.post('http://localhost:3000/user/login', user).map(
      res=> res
    )
}

Rest API:

exports.user_login = (req, res, next) => {
  User.find({ email: req.body.email })
    .exec()
    .then(user => {
      if (user.length < 1) {
        return res.status(401).json({
          message: "Auth failed"
        });
      }
      bcrypt.compare(req.body.password, user[0].password, (err, result) => {
        if (err) {
          return res.status(401).json({
            message: "Auth failed"
          });
        }
        if (result) {
          const token = jwt.sign(
            {
              email: user[0].email,
              userId: user[0]._id
            },
            process.env.JWT_KEY,
            {
              expiresIn: "1h"
            }
          );
          return res.status(200).json({
            success: true,
            message: "Auth successful",
            token: token,
          });
        }
        res.status(401).json({
          message: "Auth failed"
        });
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
};

1 个答案:

答案 0 :(得分:1)

有效负载是您的帖子请求的正文。正文是您发送的第二个参数(user):

this.http.post('http://localhost:3000/user/login', user)

用户对象由您自己填充在组件中:

const user = {
  "email" : this.loginform.get('name').value,
  "password" : this.loginform.get('password').value
}

文档:https://angular.io/api/common/http/HttpClient#post