display node server data to front-end | SoloLearn: Learn to code for FREE!


display node server data to front-end

I was wondering is there a way to display data fetched by my node server, and display it to my front-end ? Like using something like a javascript frontend framework or EJS

5/21/2020 8:16:34 AM


3 Answers

New Answer


Pass them like that Your db query Res.render('index.ejs',{data:data}); Ejs file <% data.forEach((d)=>{ <input type = "text" value = "<%=d.name%>"> <%})%>


1) Firstly install packages express, ejs, path, node-fetch for node Setup the following files, server.js and index.ejs // server.js const express = require("express"); const path = require('path'); const fetch = require('node-fetch'); const app = express(); app.use(express.static("public")); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // GET '/' app.get("/", (req, res) => { fetch('https://jsonplaceholder.typicode.com/users') .then(res => res.json()) .then(users => { res.render('index', {users: users}); }); }); // listen for requests const listener = app.listen(3000, () => { console.log("Your app is listening on port 3000"); });


2) add ejs file // views/index.ejs <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Fetch Api from Express server"> <title>Fetch Api from Express server</title> <link rel="stylesheet" href="/style.css"> </head> <body> <header><h2>Fetch Api from Express server</h2></header> <main> <h2>User List</h2> <p>Api fetch from https://jsonplaceholder.typicode.com/users</p> <section class="dreams"> <ul id="dreams"> <% users.forEach(function(user) { %> <li><%= user.name %></li> <% }) %> </ul> </section> </main> </body> </html> // To start the server, run command: node Check out and run express with ejs codes here.. https://glitch.com/~api-fetch-by-server https://code.sololearn.com/WYNk8mU9SCrB/?ref=app