View nodejs data in front-end using express without using front-end framework

Asked

Viewed 804 times

0

I wonder if there is any way to pass data manipulated in the back-end in nodejs to an html file without using front-end framemework. In my researches I found examples using jquery.

  • Your question is unclear... Please edit it by adding a little more information. :)

1 answer

0


One way to pass Node data to your frontend would be to use EJS. EJS uses HTML files with the EJS extension, and within them, you can send or receive data from your routes defined in your Express/Node project.

To install, as you already have the Express installed, you can do so:

npm install ejs express-ejs-layouts --save 

Here’s an example of what a route would look like (GET):

app.get('/about', (req, res) => {
  var users = [{
    name: faker.name.findName(),
    email: faker.internet.email(),
    avatar: 'http://placekitten.com/300/300'
  }, {
    name: faker.name.findName(),
    email: faker.internet.email(),
    avatar: 'http://placekitten.com/400/300'
  }, {
    name: faker.name.findName(),
    email: faker.internet.email(),
    avatar: 'http://placekitten.com/500/300'
  }]

  res.render('pages/about', { usuarios: users })
})

In this example, the "user" array is sent to a file located in "pages/about.ejs". To this file, a variable called "users" is sent".

Within "pages/about.ejs", this array is displayed as follows:

<div class="jumbotron text-center">
     <h1>O Time!</h1>
     <div class="row">
     	<% for (usuario of usuarios){%>
     	  <div class="col-sm-4">
     	  	<h2><%= usuario.name %>
     	  	<img class="img-responsive" style="height: 250px" src="<%= usuario.avatar %>">
     	  </div>
     	<% } %>
     </div>
  </div>

Here is a step by step, showing how to create a layout using EJS

http://tsdn.tecnospeed.com.br/blog-da-consultoria-tecnica-tecnospeed/post/utilizando-a-engine-ejs-para-aplicacoes-em-nodejs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.