I am trying to login to my application hosted locally(for now) using ionic framework.
This is my nodejs backend code for logging in which was meant for web application but now I am making it for android platfrom as well
// 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 code in ionic
<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>
The login function which is called:
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));
}
}
}
if I use .subscribe method for the post it gives an error other login method:
login() {
this.http.post('10.222.103.169:8080/login', JSON.stringify({ email: this.email, password: this.password }))
.subscribe(data => {
console.log(data);
});
}
Runtime Error Error in ./LoginPage class LoginPage - caused by: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL
but the link is correct and works now the problem is that it's not even sending the post request to the server.
PS: I am new to angular2.
You have to do it as shown below.This is the Angular way of post
method.Hope code is self explanatory.If you need any help feel free to comment below.
//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);
}