>我正在尝试使用离子框架登录到本地(目前(托管的应用程序。
这是我用于登录的nodejs后端代码,用于Web应用程序,但现在我也为android平台制作了它
// process the login form
app.post('/login', passport.authenticate('local-login', {
successRedirect: '/profile', // redirect to the secure profile section
failureRedirect: '/login', // redirect back to the signup page if there is an error
failureFlash: true // allow flash messages
}));
离子中的 HTML 代码
<ion-item>
<ion-input type="text" placeholder="Email" name="email" [(ngModel)]="email"></ion-input>
</ion-item>
<ion-item>
<ion-input type="password" placeholder="Password" name="password" [(ngModel)]="password"></ion-input>
</ion-item>
</ion-list>
调用的登录函数:
login() {
this.http.post('10.222.103.169:8080/login', JSON.stringify({ email: this.email, password: this.password }))
.map((response: Response) => {
let user = response.json();
console.log(user);
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
}
}
如果我对帖子使用 .subscribe 方法,它会给出错误其他登录方式:
login() {
this.http.post('10.222.103.169:8080/login', JSON.stringify({ email: this.email, password: this.password }))
.subscribe(data => {
console.log(data);
});
}
./LoginPage 类 LoginPage 中的运行时错误错误 - 由:失败 在"XMLHttpRequest"上执行"打开":无效的URL
但是链接是正确的并且有效现在的问题是它甚至没有向服务器发送 POST 请求。
PS:我是 angular2 的新手。
您必须按如下所示进行操作。这是post
方法的角度方法。希望代码是不言自明的。如果您需要任何帮助,请随时在下面发表评论。
//login
loginUser(email: string, password: string): Observable<any> {
let headers = new Headers();
headers.append('content-type', 'application/json');
let body = { email: email, password: password };
let options = new RequestOptions({ headers: headers });
let url = this.authenticationEndPoint + encodeURI(username) + '&password=' + encodeURI(password);
return this.http.post(url, body, options)
.map(this.extractData)
.catch(this.handleError);
}
//to extract data
private extractData(res: Response) {
let body = res.json();
return body || {};
}
//to handle error
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
将参数分配给 URLSearchParams 对象
login() {
let params = new URLSearchParams;
params.append('email',this.email);
params.append('password',this.password);
this.http.post('10.222.103.169:8080/login',search:params )
.map((response: Response) => {
let user = response.json();
console.log(user);
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
}
}