byteseeker
byteseeker

Reputation: 1385

How to send multiple POST requests in JavaScript

I have a html form that contains some fields to include user credentials and a file input, something like this:

<form action="">
    username: <input type="text" name="name" id="name"> <br/>
    secret key: <input type="password" name="key" id="key"> <br/>

    <input type="file" name="actual_upload" id="actual_upload">
</form>

I want to upload the file to server S2 only after the user credentials has been verified, and a unique token has been generated by another server S1 (returns the token as JSON).

One way I thought of doing this is posting it to S1 and then forward the request from S1 to S2. But this way I have to receive the complete request in S1, which unnecessarily increases S1's load.

If I put the user credentials in the request header instead of the request body, is there a way to send only the headers to S1 and then after receiving the token, use that to send the file to S2 ? Or is there another way?

Upvotes: 2

Views: 7578

Answers (1)

bytesandcaffeine
bytesandcaffeine

Reputation: 195

As others have mentioned in comments, you can use either AJAX or Promises. A simple implementation would be to use the fetch API.

Here's a sample code structure that you can use (I'm assuming you do have a submit button in your form):

document.getElementById('submit').addEventListener('click', uploadFile);

function uploadFile() {

    event.preventDefault();

    let name = document.getElementById('name').value;
    let key = document.getElementById('key').value;

    let S1Url = // endpoint where token will be generated 

    fetch(S1Url, {
        method: 'GET',
    }).then(function(response){
        // extract token from JSON response
        // return token
    }).then(function(token) {
        let S2Url = // endpoint where file will be uploaded

        // file that has been selected in the form
        let input = document.querySelector('input[type="file"]');

        let data = new FormData();
        data.append('file', input.files[0]);

        return fetch(S2Url, {
            method: 'POST',
            body: data
        });

    }).then(function(response){
        // do something with the response
    }).catch(function(error) {
        // handle error
    });
}

Checkout this MDN documentation where there are good number of examples that uses fetch API. Also, take a look at this answer here.

Upvotes: 1

Related Questions