...
/Solution Review: Making POST and GET Requests to Public REST API
Solution Review: Making POST and GET Requests to Public REST API
Learn to make API requests to a public REST API.
We'll cover the following...
We'll cover the following...
import fetch from "node-fetch"
import express from "express"
const app = express();
const port = 5000;
//Make POST Request
let course = {
userId: 101,
title: "MEAN Stack course on Educative",
completed: true
}
fetch('https://jsonplaceholder.typicode.com/todos', {
method: 'POST',
body: JSON.stringify(course),
headers: { 'Content-Type': 'application/json' }
}).then(res => res.json())
.then(json => console.log("Post Request to Send an Object to the Server", json))
.catch(err => console.log(err));
//Make GET Request
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((json) => {
console.log("Get Request for First user in the array:");
console.log(json[0]);
});
app.listen(port, () => {
console.log(`Listening on Port, ${port}`);
});
Solution displaying the responses in the console.
Explanation for POST request
-
We start by importing the
node-fetchandexpressnpm packages in line 1 and line 2, respectively. -
In line 4 and line 5, we initialize
express()...