1

I'm trying to get values from nodejs into HTML. I've seen lot of answers, but none of them is working.

here what I've done so far:

index.html

    <!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='main.css'>

</head>
<body>

    <div> 
          <a id="test" name="test"> <%=name%></a>


    </div>
</body>
</html>

app.js

   const express =require('express')
const app = express();
var os = require( 'os' );
var path = require('path')
const PORT = process.env.PORT ||2000;


app.engine('html', require('ejs').renderFile);

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


app.get('/test', (req, res)=> {

    var name = 454;

    res.render( "/index.html", {name:name});

  });

app.listen(2001) 

I don't get what I'm doing wrong. but it doesn't work as expected. any idea how may I solve this ? thanks in advance !

1 Answer 1

2

First, create a folder views and put your index.ejs right there (though, I am not sure, the extension have to be .ejs).

Then set the engine with:

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

And change your routing to:

app.get('/', (req,res) => {
    res.render('index', { name: 'Test' });
});

Edit: I have used the express application generator and also checked Using template engines with Express.

Edit: According to the extension .ejs:

One thing to note is that all files in which ejs syntax are used in must be saved with a .ejs extension [...]

Taken from Using EJS as a Template Engine in your Express App, not from the official docs.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your answer. It did work, but my problem is that I need to integrat it in already made html, is there a way to render just a specific element in the html page? thanks in again !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.