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(.....)
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 object in the request initializer.body property of the request initializer.method property in the request initializer.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...
});