-1

I just start first project with Angular 2 and I've trouble with services.

I've an http service called when submitting a form, but when I submit the form, the http request is executed twice.

login.component.html

<form method="post" (ngSubmit)="login()">
    <input type="email" [(ngModel)]="user.email" id="email" name="email" placeholder="Email" class="input input--block input--text-center" required >
    <input type="password" [(ngModel)]="user.password" name="password" placeholder="Password" id="passord" class="input input--block input--text-center" required>
    <input type="submit" value="Connect" class="btn btn--block">
</form>

login.component.ts

login() {
    this.service.login(this.user.email, this.user.password)
        .subscribe( res => {
            if (res == null) {
                alert("Fail");
            } else {
                res.password = null;
                this.user = res;
                alert("Welcome "+this.user.firstname+"!");
        }
    });
}

user.service.ts

login(email:string, password:string): Observable<User> {
    let CryptoJS = require("cryptojs");
    let sha512 = CryptoJS.algo.SHA512.create();
    sha512.update(password);
    password = sha512.finalize().toString();
    return this.http.post(`${this.baseUrl}/user/login`, 
        {email: email.trim(), password: password.trim()}, 
        {headers: this.headers })
    .map(res => res.json())
    .catch(this.handleError);
}

I added some console.log("test"); to check which method is called twice and it appears that there is no method called twice, just the HTTP request that I can see in the network console of the web browser

Maxime
  • 1,172
  • 1
  • 13
  • 40

1 Answers1

2

I think you are confusing OPTIONS and POST requests with a double POST request

OPTIONS requests are essential for Cross-Origin Resource Sharing

The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. Additionally, for HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether "credentials" (including Cookies and HTTP Authentication data) should be sent with requests.

Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

eko
  • 34,608
  • 9
  • 60
  • 85