Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

express

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'));
});
like image 499
Hessam Hosseini Avatar asked Oct 13 '21 21:10

Hessam Hosseini


People also ask

How do I send data from server to client in node JS?

Methods to send response from server to client are:Using send() function. Using json() function.

Which Express method sends a response to the client?

Response Render method This method renders a view and sends the rendered HTML string to the client.

Which method is used to send the content in Express JS?

send() Function. The res. send() function basically sends the HTTP response. The body parameter can be a String or a Buffer object or an object or an Array.


Video Answer


1 Answers

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}`);
    }
});
like image 160
Hessam Hosseini Avatar answered Oct 23 '22 12:10

Hessam Hosseini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!