angular 2服务不发送数据 - 不可处理的实体

时间:2017-02-09 17:41:29

标签: api angular service

我正在尝试使用表单在http://localhost:8000/api/signin上发送数据(电子邮件,密码) 但它不断回复我这个回应

Unprocessable Entity
{"email":["The email field is required."],"password":["The password field is required."]}

服务

 login(email:string,password:string){
    console.log(email,password);
    return this._http.post('http://localhost:8000/api/signin',JSON.stringify({email:email,password:password}))
    .map(res =>{
        // login successful if there's a jwt token in the response
         let user = res.json();
         if(user && user.token){
               localStorage.setItem('currentUser',JSON.stringify(user));
           }
    });
}

Login.Component.ts

 login(){
  console.log(this.model.email,this.model.password);
  this.authenticationservice.login(this.model.email,this.model.password)
    .subscribe(
        data => {
          this.router.navigate([this.returnUrl]);
        });

形式

<div class="col-md-6 col-md-offset-3">
<h2>Login</h2>
<form name="form" (ngSubmit)="login()">
    <div class="form-group">
        <label for="email">Email</label>
        <input type="email" class="form-control" name="email" [(ngModel)]="model.email" required />
    </div>
    <div class="form-group">
        <label for="password">Password</label>
        <input type="password" class="form-control" name="password" [(ngModel)]="model.password" required />
    </div>
    <div class="form-group">
        <button class="btn btn-primary">Login</button>
    </div>
    <div *ngIf="error" class="alert alert-danger">{{error}}</div>
</form>

邮递员的回应 http://image.prntscr.com/image/b6c5a8d985834283aa0501c8cb4caed9.png

2 个答案:

答案 0 :(得分:0)

试试这个:

let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = {
    headers: headers
};
let body = JSON.stringify({email:email,password:password});
return this.http.post(url, body, options).map(...);

答案 1 :(得分:0)

在您的请求中添加Content-Typeapplication/json标头:

login(email:string,password:string) {
        let bodyString = JSON.stringify({ email: email, password: password });
        let headers = new Headers({ 'Content-Type': 'application/json' });

        return this._http.post('http://localhost:8000/api/signin', bodyString, {headers: headers})
            .map(res =>{
            // login successful if there's a jwt token in the response
                let user = res.json();
                if(user && user.token){
                    localStorage.setItem('currentUser',JSON.stringify(user));
                }
            });
}