0

Please forgive me as Im not an expert in coding but Im trying to send JSON data from a file to a javascript variable on my website.

Im using NodeJS & EJS but when the variable is filled on the browser, all the " are replaced with &#34 and an error appears.

NodeJS Server.js

// Load Node modules
var express = require('express');
const ejs = require('ejs');
const fs = require('fs');

function read(path) {
    const fileContent = fs.readFileSync(path);
    const array = JSON.parse(fileContent);
    return array;
}

var data = read('data.txt');
data=JSON.stringify(data);
console.log(data);

// Initialise Express
var app = express();
// Render static files

app.use(express.static('public'));
// Set the view engine to ejs
app.set('view engine', 'ejs');
// Port website will run on
app.listen(8080);

// *** GET Routes - display pages ***
// Root Route
app.get('/', function (req, res) {
    res.render('pages/index',{data: data});
});

html script to insert the data.

<script>
    var employee= <%=(data)%>;
    console.log(employee);
  </script>

When I console log data in Node I get

[{"employee":{"name":"John White","idNumber":5124,"married":true}},{"employee":{"name":"Billy Brown","idNumber":3429,"married":false}}]

The information imported into the browser has replaced all the " with &#34.

I appreciate any help you guys could give. I've looked all day to try and find out why this is happening.

Regards.

Darwinian78
  • 11
  • 1
  • 1
  • 2
  • try using tags `<%-` that doesn't escape value, and also use `JSON.stringify`: `var employee= <%- JSON.stringify(data)%>;` check: https://stackoverflow.com/questions/11289793/accessing-ejs-variable-in-javascript-logic – traynor Jul 24 '22 at 07:09
  • @traynor You would however still need to escape `` if you don't trust the input – Bergi Jul 24 '22 at 13:07
  • @Bergi true, it's discussed in the answers I linked to, as well as to use AJAX, which is also how I'd do it.. – traynor Jul 24 '22 at 15:52
  • @traynor Which of the answers or comments discuss that? I saw no mention of the `` tag anywhere – Bergi Jul 24 '22 at 17:05
  • @Bergi no, I meant the issue of trust/security is discussed. in the comments in the first answer – traynor Jul 24 '22 at 17:31

0 Answers0