Http.post posts data twice, why?

Hi there,

I’ve used the code below to save an object called position to a locally hosted json-server. Now I can successfully post to the array but every time that the post method is called, the data is saved twice causing duplicate entries. How do I prevent the duplicate entries?

saveToServer(pos) {
    this.position = pos;
    console.log("sendPosToServer" + JSON.stringify(this.position));
    var headers = new Headers();
    headers.append("Accept", 'application/json');
    headers.append('Content-Type', 'application/json');
    let options = new RequestOptions({ headers: headers});
    console.log("post params " + JSON.stringify(this.position));

    console.log("complete position, save");

    /*
    this.http.post(baseURL + 'positions', this.position, options)
              .map(res => console.log("first"))
              .share();
    */
      
      this.http.post(baseURL + 'positions', this.position, options)
        .subscribe(data => {
          console.log("First spot " + data['_body']);
        }, error => {
          console.log(error);
        });
    console.log("bottom of sendPosToServer");
  }

My guess would be CORS. It’ll send out an initial OPTIONS request, and then send your proper request.

I believe the way to handle it is to just check to see if its an OPTIONS request on your server, and don’t save the data in that case.

You can read more here:

There could be many reasons for this. One would be - did you ensure that the provider that serves this post function is a singleton? and that its not initialized twice somewhere in your code?

Basically I would start by reviewing if the provider has proper initialization.

How many times does this line execute?

This line executes twice.

Also encountered this issue, I thought it was only me. I’ve used different approaches but still firing twice. Any idea on how to fixed or avoid this “issue”?

I have resolved mine. I think its a CORS “issue” and can only be fixed in the API server side. In my case I disabled the REQUEST_OPTION method in allowed http method and it fixed by problem.

Hi,

You resolve this issue? I have the same problem for 3 days, read many docs and nothing…

Thanks.

Please post a minimal reproducible case.

1 Like

Hi @rapropos

My problem is a Module registered for two others pages, this other pages use the same service. I remove page Module and works fine now.

Obs.: Share(), publish().refCount(), CORS… nothing works.

I guess normally (to create singleton service) you want to import / init services in your core app.module.ts and only import services in required places.