DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

mishrasatyam
mishrasatyam

Posted on

Request using node-fetch with async/await

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

Top comments (0)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.