Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send data to client with expressJS

How would I go into retrieving data from expressJS? That is without it getting overwritten, or redirecting a user.

<html>
    <body>
        <h1>Retrieved data</h1>
    </body>
</html>

for example how would i go into adding it if the server side looks like this?

var express = require("express");
var app = express();

app.get("/", function (req, res) {
    res.sendFile(__dirname + "/index.html");
    //how do i add data to the <h1> tag
});

app.listen(10022, function () {
    console.log("server is up");
});
like image 246
Felipe Garcia-Diaz Avatar asked Sep 26 '22 12:09

Felipe Garcia-Diaz


1 Answers

You wouldn't be able to do it with a .html file. You'd need an EJS file. The markup for that would look like this.

<html>
    <body>
        <h1>Retrieved <%= data %></h1>
    </body>
</html>

Then you'll need the ejs module. Run the following NPM command.

npm install ejs

So change your index.html to index.ejs, make sure it's in a directory named views, and then modify your server side code to this.

var express = require("express");
var app = express();

app.set("view engine", "ejs");

app.get("/", function (req, res) {
        res.render("index", {data: 'This is the data'});
});

app.listen(10022, function () {
        console.log("server is up");
});

EJS is a templating language that converts to HTML, taking the data object you've passed in through your render method, rendering it server side, and then sending it to the browser.

like image 73
whatoncewaslost Avatar answered Sep 30 '22 07:09

whatoncewaslost