简体   繁体   中英

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.

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

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"
}'

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)

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM