DEV Community

mishrasatyam
mishrasatyam

Posted on

8 2

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more