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");
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With