Translate curl to fetch

TODO: collapasable, copyable, download, etc

I have a curl that works with -u username:password how would I translate that into the intputs to fetch?If you have a curl command that looks like this:

curl -u username:password http://example.com/resource

The -u flag specifies the credentials for basic authentication. You can translate this into a JavaScript fetch call using the Authorization header with "Basic" followed by a base64 encoded string of the username and password concatenated with a colon (:).

Here's how you'd do it:

const url = "http://example.com/resource";
const username = "username";
const password = "password";

// Base64 encode the credentials
const base64Credentials = btoa(username + ":" + password);

fetch(url, {
  method: 'GET',
  headers: {
    'Authorization': 'Basic ' + base64Credentials
  }
})
.then(response => response.json()) // assuming server responds with json
.then(data => console.log(data))
.catch(error => console.error('There was an error!', error));

In the above code:

  • The btoa function is a built-in JavaScript function that encodes a string as base64.
  • The Authorization header is constructed using the base64 encoded credentials.
  • You can then handle the response or errors as required by your application.

Make sure that if you're working in a browser environment, the server supports CORS if you're making cross-origin requests. If the server does not support CORS, you'll need to use some server-side solution or service that acts as a proxy.

Translate curl to fetch created at Tue Jan 20 1970 15:03:56 GMT+0000 (Coordinated Universal Time)

Related Chats

Translate curl to fetch 0.999

Curl with Origin Header 0.536

SvelteKit REST Proxy 0.416

New chat 0.400

Node.js POST Request Stream 0.393

Popular NodeJS HTTP Libraries 0.385

Stream REST Data in JavaScript 0.377

Bash Script Curl 100 0.350

Base64 encoded values. 0.349

React Auth Types Enum 0.348