关于 api:angular 2 服务不发送数据 – 无法处理的实体

angular 2 service does not send data - Unprocessable Entity

我正在尝试使用表单在 http://localhost:8000/api/signin 上发送数据(电子邮件、密码)
但它一直向我返回此响应

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

服务

1
2
3
4
5
6
7
8
9
10
11
 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

1
2
3
4
5
6
7
 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]);
        });

表格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Login
<form name="form" (ngSubmit)="login()">
   
        <label for="email">Email</label>
        <input type="email" class="form-control" name="email" [(ngModel)]="model.email" required />
   
   
        <label for="password">Password</label>
        <input type="password" class="form-control" name="password" [(ngModel)]="model.password" required />
   
   
        <button class="btn btn-primary">Login</button>
   
    {{error}}
</form>

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


Content-Type : application/json 标头添加到您的请求中:

1
2
3
4
5
6
7
8
9
10
11
12
13
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));
                }
            });
}

试试这个:

1
2
3
4
5
6
7
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(...);