Angular 2 http.post发送空对象

时间:2017-01-09 12:26:30

标签: angular express angular2-http

这是一个authservice登录,取from here

login(email: string, password: string): Observable<boolean> {
    return this.http.post(
        apiURL + '/admin/login',
        JSON.stringify({ email: email, password: password }))
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let token = response.json() && response.json().token;
            if (token) {
                // set token property
                this.token = token;

                // store username and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({ email: email, token: token }));

                // return true to indicate successful login
                return true;
            } else {
                // return false to indicate failed login
                return false;
            }
        });
}

在我的组件中,我正在尝试订阅:

login() {
    this.loading = true;
    console.log(this.model);
    this.authenticationService.login(this.model.email, this.model.password)
      .subscribe(result => {
        if(result === true) {
          this.router.navigate(['/']);
        } else {
          this.error = 'Username or password is incorrect';
          this.loading = false;
        }
      });
  }

我已经在线上完成了控制台日志,以确定数据是否实际被传递,是的。一切都很好。

除外,发送的数据仅为{ }

根据我的Express控制台,这是req.body唯一的事情。 req.headers表示内容类型正确,即Content-Type: application/json

我尝试使用POSTMan向API端点发送相同的json请求。工作正常。

Angular 2的http.post袖子还有其他技巧吗?

上面的代码出了什么问题?

1 个答案:

答案 0 :(得分:4)

在这里发布答案可能对某人有所帮助。感谢@cartant的指点。我只需要仔细观察:

  • 我不需要显式设置标头。默认情况下,帖子发送login(email: string, password: string): Observable<boolean> { // this is optional // let headers = new Headers({ 'Content-Type': 'application/json' }); // let options = new RequestOptions({ headers: headers }); return this.http.post( apiURL + '/admin/login', { email: email, password: password }, // options ) .map((response: Response) => { // login successful if there's a jwt token in the response let token = response.json() && response.json().token; if (token) { // set token property this.token = token; // store username and jwt token in local storage to keep user logged in between page refreshes localStorage.setItem('currentUser', JSON.stringify({ email: email, token: token })); // return true to indicate successful login return true; } else { // return false to indicate failed login return false; } }); }
  • DID NOT 必须对要发送的数据进行字符串化。

    using System.Linq;
    using NHibernate;   
    
    public static T GetInstanceFromCache<T>(this ISession session, object key) where T : class
    {
        var entity = session.GetSessionImplementation().PersistenceContext.EntitiesByKey.SingleOrDefault(x => x.Value is T && x.Key.Identifier == key);
        return entity as T;
    }