0

I have created form

<div class="clr-row campform">
    <form (ngSubmit)="onSubmit(f)" #f="ngForm">
        <div class="clr-col-12 gutterpadl gutterpadr">
            <h5>List Name</h5>
            <input type="text" name="listname" ngModel class="borderfield" required placeholder="Enter List Name">
        </div>
        <div class="clr-row autobtn">
            <button type="submit" class="btn btn-primary">Submit</button>
            <button type="reset" class="btn">Cancel</button>
        </div>
    </form>
</div>

TypeScript Code

onSubmit(form: NgForm) {
    const list = { 'listname': form.value.listname };
    this.dataManage.createList(list).subscribe(response => { console.log(response) });
    this.loadData();
  }

Service Code

createList(listname) {
    return this.httpClient.post(this.baseURL + 'data_list/create', listname, { headers: this.authService.getCredentialHeaders() });
  }

When I click on submit button, and I check on browser developer tools section. In the network I see that request was sent twice, first time blank (No any values sent.) and second time with values.

First Image

You can see here create run twice. When I click on first create call

Second Image

I get the blank response from server, And when I click on second create call,

Third Image

I got an array. I am unable to understand why it is sending request first time with blank data and second time with correct data. I only need one call with correct data.

Anand agrawal
  • 434
  • 5
  • 21
  • 1
    Sounds like the pre-flight request done by browsers. See [this](https://stackoverflow.com/questions/29954037/why-is-an-options-request-sent-and-can-i-disable-it) for more information. Check the method of the first request. If it is part of the pre-flight check it should have the `OPTIONS` method. – Mathyn Jul 03 '19 at 13:06
  • Exactly what @Mathy said. It check whether request is trusted, if yes then only call the actual call. – Saima Haji Jul 03 '19 at 13:11

2 Answers2

1

The blank request is the OPTIONS request that serves to ping the server to see if its there and if its safe to send the payload also called a preflight request. The second request is the actual POST request with the data.

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests

Qellson
  • 532
  • 2
  • 7
1

If you go to the headers tab of any network request, then you will see the first request is OPTIONS type and the second request is whatever the method you have specified. The OPTIONS request is kind of communication test to the server or that particular end point. https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

Ashish Sharma
  • 443
  • 5
  • 12