Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

fetch data from api url

fetch('https://jsonplaceholder.typicode.com/posts').then(function (response) {
	// The API call was successful!
	return response.json();
}).then(function (data) {
	// This is the JSON from our response
	console.log(data);
}).catch(function (err) {
	// There was an error
	console.warn('Something went wrong.', err);
});
Comment

js how to get data fetch

// way 1
const getData = async (url) => {
  const response = await fetch(url)
  const json = await response.json()

  return json
}

const url = `https://jsonplaceholder.typicode.com/posts?userId=3`

try {
  const data = await getData(url)
  console.log(data)
} catch (error) {
  console.log(error.message)
}

/* ------------ Way 2 --------------- */
const getData = (url) =>
  new Promise((resolve, reject) => {
    fetch(url)
      .then(response => response.json())
      .then(json => resolve(json))
      .catch(error => reject(error))
  })

const url = `https://jsonplaceholder.typicode.com/todos?completed=true&userId=2`

getData(url)
  .then(data => console.log(data))
  .catch(error => console.log(error.message))
Comment

PREVIOUS NEXT
Code Example
Javascript :: class MyComponent extends React.Component { } ... what is the ES5 equivalent of this * 
Javascript :: get url query params js 
Javascript :: angular create component without test 
Javascript :: write files in node js 
Javascript :: check if element is on screen 
Javascript :: javascript print numbers in the given range 
Javascript :: jquery select change get selected value 
Javascript :: vue + change router link active class 
Javascript :: how to call a javascript function in html without any event 
Javascript :: initialize json array 
Javascript :: document getelementsbyclassname not getting all elements 
Javascript :: uuid for react native 
Javascript :: get input in terminal nodejs 
Javascript :: javascript set attribute href 
Javascript :: javascript generate random hex 
Javascript :: calculate distance between two coordinates formula javascript 
Javascript :: in which language python is written 
Javascript :: monitor changes made to object 
Javascript :: node-schedule-tz print jobs 
Javascript :: check radio button is checked jquery 
Javascript :: ajax call with form data 
Javascript :: simple AES encryption javascript 
Javascript :: javascript opacity 
Javascript :: jquery get link href value 
Javascript :: Twilio room does not disconnect / Webcam LED remains on 
Javascript :: jquery on hover event 
Javascript :: last element of array javascript 
Javascript :: regex for ip address javascript 
Javascript :: gradle json simple dependency 
Javascript :: instance use in_array in javascript 
ADD CONTENT
Topic
Content
Source link
Name
3+9 =