Francesco_Lastrino
Francesco_Lastrino

Reputation: 45

Curl -u Request in javascript

I need to perform a curl request like this:

curl -u "apikey:{apikey}" "{url}"

How can i do this in javascript? In particular i have some trouble to handle the -u curl field into javascript request.

Upvotes: 0

Views: 2378

Answers (4)

spender
spender

Reputation: 120508

To expand on @whirlwin's answer, you can generate the required header value with the following code:

const apiKey = "someApiKey"
const basicAuthValue = Buffer.from(`apikey:${apikey}`).toString("base64");
const authHeaderValue = `Basic ${basicAuthValue}`

//node
let requestOpts = {/* node http options */}; 
requestOpts = { 
    ...requestOpts, 
    headers: { 
        ...requestOpts.headers, 
        "Authorization": authHeaderValue 
    } 
}

//browser
const request = new XMLHttpRequest();
request.setRequestHeader("Authorization", authHeaderValue)

Upvotes: 1

Prasanth Ganesan
Prasanth Ganesan

Reputation: 551

Here is a solution with vanilla js.

var request = new XMLHttpRequest();
request.open("GET", yourUrl, true);
request.setRequestHeader("apikey","someapikey778229"); 
request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        //do something here;
    }
};
request.send();

Upvotes: 0

Johan
Johan

Reputation: 5

You cant call javascript from curl. Are you sure you want to call javascript and not post json?

ex

curl -i -X POST -u user:userpass -H 'Accept: application/json' -H 'Content-type: application/json' --url 'http://myserver' -d '{
  apikey:"ddasds",
  url:"http://myserver"
}'

Upvotes: 0

whirlwin
whirlwin

Reputation: 16531

You will have to specify a basic auth header (Authorization: Basic <base64 of apikey:value>) with the API key when using JavaScript. If you are using XMLHttpRequest, have a look at this this: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader

Upvotes: 2

Related Questions