[英]Angular 2 http.post sending empty object
这是一个authservice登录名, 从此处获取 :
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
套还有其他技巧吗?
上面的代码有什么问题?
在此处发布答案可能会对某人有所帮助。 感谢@cartant提供的指针。 我只需要仔细看一下:
Content-Type: application/json
我不必对要发送的数据进行分类。
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; } }); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.