What’s the best way to perform a `curl` request in JavaScript?

I want to replicate a curl request (with headers like ‘Authorization’) in JavaScript, similar to how it’s done in PHP. How can I send such a request and handle the returned JSON data for further processing with jQuery?

The fetch API is modern, clean, and supports promises. Here’s how you can send a GET request with custom headers like Authorization and handle the JSON response:

// Define the API URL and authorization token
const url = 'https://example.com/api/endpoint';
const token = 'Bearer your_authorization_token_here';

// Perform the fetch request
fetch(url, {
  method: 'GET', // or 'POST', 'PUT', etc.
  headers: {
    'Authorization': token, // Add the Authorization header
    'Content-Type': 'application/json' // Optional, depending on the API
  }
})
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText);
    }
    return response.json(); // Parse JSON response
  })
  .then(data => {
    console.log('Success:', data); // Process the data
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

The fetch function takes a URL and an options object where you can add headers like Authorization. The .then() blocks handle the response—first checking if it’s OK, then converting it to JSON. If something goes wrong, the catch() block handles the error.

@neha.jlly While fetch is generally preferred, you can still use XMLHttpRequest for better compatibility with older browsers.

const url = 'https://example.com/api/endpoint';
const token = 'Bearer your_authorization_token_here';

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader('Authorization', token);
xhr.setRequestHeader('Content-Type', 'application/json');

// When the request is successful, process the response
xhr.onload = function() {
  if (xhr.status >= 200 && xhr.status < 300) {
    var response = JSON.parse(xhr.responseText); // Parse the JSON response
    console.log('Success:', response); // Process the data
  } else {
    console.error('Request failed with status:', xhr.status);
  }
};

// In case of an error, log it
xhr.onerror = function() {
  console.error('Request failed');
};

// Send the request
xhr.send();

With XMLHttpRequest, you can add custom headers using setRequestHeader.

The onload function runs when the request is successful, while onerror handles network problems.

You’ll also need to manually parse the response using JSON.parse().

If you’re already using jQuery, you can use $.ajax() to make HTTP requests easily, including setting custom headers when needed.

const url = 'https://example.com/api/endpoint';
const token = 'Bearer your_authorization_token_here';

$.ajax({
  url: url,
  type: 'GET', // or 'POST', etc.
  headers: {
    'Authorization': token,
    'Content-Type': 'application/json'
  },
  success: function(data) {
    console.log('Success:', data); // Process the data
  },
  error: function(xhr, status, error) {
    console.error('Request failed:', error);
  }
});

$.ajax() simplifies setting headers and handles success and error cases through the success and error callbacks.

Like fetch, you can set the Authorization header and handle the JSON response in the success callback.