DEV Community

loading...

Request using node-fetch with async/await

mishrasatyam
Full stack developer ,technologies : python,node js, javascript, html, css , bootstrap4, mongo db, influx db etc
・1 min read

You might have used fetch on client side applications. To use fetch on server side we can use node-fetch library. Let me show basic examples using async/await .

GET request

const fetch = require('node-fetch');
async function get_request(){
  const url = 'http://get-request-url.com'
  const res = await fetch(url);
  const data = await res.json();//assuming data is json
  console.log(data)
}
Enter fullscreen mode Exit fullscreen mode

POST request

const fetch = require('node-fetch');
async function post_request(){
  const url = 'http://post-request-url.com'
  const body = {some_var:"some_value"}
  const res = await fetch(url,{method:'POST',body:JSON.stringify(body),headers: { 'Content-Type': 'application/json' }});
  const data = await res.json();//assuming data is json
  console.log(data)
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)