How do I make an HTTP request in Javascript?

There are several ways to make an HTTP request in JavaScript. One of the most popular ways is to use the fetch() method, which is a built-in function in modern web browsers. Here's an example of how you can use fetch() to make a GET request to an API endpoint:

   
fetch('https://api.example.com/data')
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error(error))


In this example, the fetch() method is used to send a GET request to the specified API endpoint. The method returns a promise that resolves with a Response object. The response.json() method is used to parse the response body as JSON. The then() method is used to handle the resolved promise and the catch() method is used to handle any errors.
Another way to make an HTTP request in JavaScript is to use the XMLHttpRequest object, which is supported by all web browsers. Here's an example of how you can use XMLHttpRequest to make a GET request:

   
var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.example.com/data');
    xhr.onload = function () {
        if (xhr.status === 200) {
            console.log(xhr.responseText);
        } else {
            console.error(xhr.statusText);
        }
    };
    xhr.send();
                                                              


In this example, the XMLHttpRequest object is used to open a GET request to the specified API endpoint. The onload event handler is used to handle the response and check the status of the request.

You can also make post request using above method by just changing the request method to post and sending the data in request body.

Please note that you may need to add CORS headers on the server side to allow a web page to make a request to a different origin.

Mudasir Abbas Turi

Hi, this is Mudasir Abbas Turi. I am a Full-stack PHP and JavaScript developer with extensive experience in building and maintaining web applications. Skilled in both front-end and back-end development, with a strong background in PHP and JavaScript. Proficient in modern web development frameworks such as Laravel and ReactJS. Proven ability to develop and implement highly interactive user interfaces, and to integrate with various APIs and databases. Strong problem-solving skills and ability to work independently and as part of a team. Passionate about staying up-to-date with the latest technologies and industry trends.

Post a Comment

Previous Post Next Post