这是一个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
袖子还有其他技巧吗?
上面的代码出了什么问题?
答案 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;
}