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.

5
  • try using tags <%- that doesn't escape value, and also use JSON.stringify: var employee= <%- JSON.stringify(data)%>; check: stackoverflow.com/questions/11289793/… Commented Jul 24, 2022 at 7:09
  • @traynor You would however still need to escape </script> if you don't trust the input Commented Jul 24, 2022 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.. Commented Jul 24, 2022 at 15:52
  • @traynor Which of the answers or comments discuss that? I saw no mention of the </script> tag anywhere Commented Jul 24, 2022 at 17:05
  • @Bergi no, I meant the issue of trust/security is discussed. in the comments in the first answer Commented Jul 24, 2022 at 17:31

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.