OrdinaryITPostAd

How do I make an HTTP request in Javascript?

 To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the more modern fetch API. Here's an example of both methods:

Using XMLHttpRequest:



javascript
var xhr = new XMLHttpRequest(); xhr.open("GET", "https://api.example.com/data", true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { var response = JSON.parse(xhr.responseText); console.log(response); } }; xhr.send();

Using fetch:

javascript
fetch("https://api.example.com/data") .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => { console.log(error); });

Both methods allow you to send HTTP requests. The XMLHttpRequest method has been around for a long time and provides more control and compatibility with older browsers. On the other hand, the fetch API is more modern and provides a simpler, promise-based syntax.

In the examples above, a GET request is made to "https://api.example.com/data", and the response is processed in the callback function. In the XMLHttpRequest example, the response is parsed as JSON using JSON.parse(). In the fetch example, the response is directly parsed as JSON using the .json() method.

Note that when making HTTP requests from a browser, you may encounter cross-origin restrictions. You might need to handle CORS (Cross-Origin Resource Sharing) if you're making requests to a different domain.

এই পোস্টটি পরিচিতদের সাথে শেয়ার করুন

পূর্বের পোস্ট দেখুন পরবর্তী পোস্ট দেখুন
এই পোস্টে এখনো কেউ মন্তব্য করে নি
মন্তব্য করতে এখানে ক্লিক করুন

অর্ডিনারি আইটির নীতিমালা মেনে কমেন্ট করুন। প্রতিটি কমেন্ট রিভিউ করা হয়।

comment url

এইটা একটি বিজ্ঞাপন এরিয়া। সিরিয়ালঃ ১