Hessam Hosseini
Hessam Hosseini

Reputation: 89

how to send data to the client side in express js?

I have some bool and string variable in the server side that should be passed to client side. how can I implement this? in my html file I want a h1 tag if my flag in the server side is true and if flag is false it just another work. at the first my flag is false. server.js:

app.get('/' , (req, res) => {
    res.sendFile(path.join(__dirname+'/views/UiOfServer.html'));
});

Upvotes: 3

Views: 177

Answers (1)

Hessam Hosseini
Hessam Hosseini

Reputation: 89

I found the anwser myself, the solution is useing EJS. because server rendering is so eazy with that. I changed my html file to EJS file and my question solved. my code is:

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.0">
    <title>example of EJS</title>
</head>
<body>
    <% if(flag){ %>
        <h1><%= username %></h1>
    <% }
    else{ %>
        <!-- some work -->
    <% } %>
</body>
</html>

server.js:

let express = require('express');
let path = require('path');
let app = express();
let router = express.Router();
app.use('/', router);
app.set('view engine', 'ejs');

const port = 2020;

app.get('/' , (req, res) => {
    res.render(path.join(__dirname+'/views/UiOfServer.ejs'), {flag: false, username: 'null'});
});

app.get('/click/' , (req, res) => {
    res.render(path.join(__dirname+'/views/UiOfServer.ejs'), {flag: true, username: 'Hessam :) '})
}

app.listen(port, (err, res) => {
    if(err){
        console.log(`Server Error: ${err}`);
    }
    else{
        console.log(`server started on ${port}`);
    }
});

Upvotes: 4

Related Questions