Http.post posts data twice, why?


#1

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");
  }

#2

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:


#3

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.


#4

How many times does this line execute?


#5

This line executes twice.


#6

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”?


#7

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.


#8

Hi,

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

Thanks.


#9

Please post a minimal reproducible case.


#10

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.


#11

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.