0

So i'm trying to post some data in my database from Angular (the backend is in PHP) using HTTPCLIENT.

The data that I want to post looks like this :

userData = { name: '', address: '', uname: '', pwd: '' };

The service that handles the request :

registerUser(userData): Observable<any> {

    return this.http.post(this.api.buildEndpoint('auth/register.php'), JSON.stringify(userData), this.api.httpOptions);

  }

And I have a api.ts file which contains everything related to the api

private readonly API_URI = 'http://localhost/users/';

public httpOptions = {

    headers: new HttpHeaders({
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json'
    })

  };

/// buildEndpoint() method

When I inspect the Network tab in the Developer Tools I see that there are two requests :

- a OPTIONS request (which does not have a body)

- and the actual POST request which contains the user information

This is normal behavior I guess, but the issue is that when I check my database I find two inserted rows , it's like the OPTIONS method had a body and posted something in the database.

I don't have this issue when I post data using Postman for example, only from the actual frontend (Angular)

I don't know what's wrong exactly, help is needed thanks !

Tony Stark
  • 43
  • 1
  • 9
  • 1
    May be this can help you understand whats going on [HTTP request from Angular sent as OPTIONS instead of POST](https://stackoverflow.com/questions/40497399/http-request-from-angular-sent-as-options-instead-of-post) – Manish Pareek Sep 28 '20 at 13:50
  • Hey @mPareek, thanks for the link. I now understand in details and solved my issue. I just had to remove the **'Access-Control-Allow-Origin': '*'** in the headers and change the content-type to **application/x-www-form-urlencoded** so that the request is not pre-flighted. Thank you – Tony Stark Sep 28 '20 at 14:47
  • Glad you solved this. I suggest you to post a answer yourself and mark it as accepted so, others can get benefit from it if they face the problem. – Manish Pareek Sep 29 '20 at 08:01
  • Hey, yes it does. i'm going to mark it as an answer. Thank you – Tony Stark Oct 01 '20 at 11:19

0 Answers0