How to get file data from url in javascript ?

How to get file data from url in javascript ?
How to get file data from url in javascript ?

To fetch data from a URL in JavaScript, you can use the fetch() function. The fetch() function is a Promise-based API that allows you to make HTTP requests to a server.

Here’s an example of how to use fetch() to get data from a URL:

fetch('https://example.com/data.json')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });

The fetch() function returns a Promise that resolves to a Response object. To get the data from the response, you can use the .json() method, which also returns a Promise that resolves to the data in JSON format.

You can also use the await keyword to wait for the Promise to resolve. Here’s an example of how to use await with fetch():

async function getData() {
  const response = await fetch('https://example.com/data.json');
  const data = await response.json();
  console.log(data);
}

getData();

Keep in mind that await can only be used inside an async function.

Leave a Reply