Node js - Send JSON from Node server to the client using Express:
const express = require("express");
const request = require("postman-request");
const expressServer = express();
expressServer.get("", (req, res) => {
res.send("Hello Express...");
});
expressServer.listen(8000, () => {
console.log("Node is up and running on 8000");
});
expressServer.get("/users", (req, res) => {
res.send([
{
first_name: "Michael",
last_name: "Lawson",
},
{
first_name: "Robert",
last_name: "Ferguson",
},
]);
});
In the above example, the Node server sending a dummy JSON to the client, but in reality, we will be getting the users from any service or the database.
Now, we will fetch users from the API and send to the client from Node server
const express = require("express");
const request = require("postman-request");
const expressServer = express();
expressServer.get("", (req, res) => {
res.send("Hello Express...");
});
expressServer.listen(8000, () => {
console.log("Node is up and running on 8000");
});
expressServer.get("/users", (req, res) => {
request("https://reqres.in/api/users?page=2", (error, response, body) => {
if (error) {
res.send("error fetching the Users");
}
res.send(JSON.parse(body));
});
});
Open the browser,
0 Comments