Rhett Jarvis
Rhett Jarvis

Reputation: 43

Send a variable to HTML with express sendfile

I'm using Node.JS, path, and express to run an HTML webpage and need to send a variable to the HTML for its use:

var client_cred_access_token = 'fakeToken';

...

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, '/public', 'homepage.html'));
});

How can I send this string variable to homepage.html?

Upvotes: 2

Views: 4055

Answers (1)

Raj
Raj

Reputation: 274

You will need a template engine middleware like pug / ejs with express to achieve this functionality.

Sample code with ejs library. Just npm i ejs

const express = require('express');
const app = new express;
const path = require('path');

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

const client_cred_access_token = 'fakeToken';

app.get('/', function (req, res) {
    res.render(path.join(__dirname, '/public', 'homepage.html'), {token: client_cred_access_token});
});

app.listen(3001);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1><%= token %></h1>
</body>
</html>

Reference: https://expressjs.com/en/resources/template-engines.html

Upvotes: 1

Related Questions