Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

334
Views
How can I convert this curl call to XML Http Request call?

I have something like this :

curl "https://test.api.amadeus.com/v1/security/oauth2/token" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}"

I want to convert it xhr object in Javascript. Can you help me ? I mean ;

xhr.open(....) 
xhr.setRequestHeader(.....) 
xhr.send(.....)
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I recommend you don't. :-) Instead, use fetch, the newer standard replacement for XMLHttpRequest. Just beware of the footgun in the API I describe here. To see how, let's look at what that curl call is doing:

  • -H defines a header.

  • -d specifies data that curl...

    ...sends...in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the con‐ tent-type application/x-www-form-urlencoded.

So looking at the fetch ways you do that:

  • Headers are defined via the headers object in the request initializer.
  • Data is sent via the body property of the request initializer.
  • You specify a POST request via the method property in the request initializer.
  • To send data compatible with application/x-www-form-urlencoded, the easiest thing is to use a URLSearchParams object.

So that gives us:

fetch("https://test.api.amadeus.com/v1/security/oauth2/token", {
    method: "POST",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    body: new URLSearchParams([
        ["grant_type", "client_credentials"],
        ["client_id", client_id],            // I'm assuming you have this in a variable
        ["client_secret", client_secret],    // Same assumption
    ]),
})
.then(response => {
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    // ...if relevant, read the response via `json` or `text` or others;
    // here I'll use `text` AS AN EXAMPLE
    return response.text();
})
.then(data => {
    // ...use the data...
})
.catch(error => {
    // ...handle/report error...
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!