I'm trying to tidy things up. So instead of having a script tag on my page with all the code inside, I'd like to insert a tag leading to a javascript file with the code that performs the desired task(s).

The problem I'm having is that I get a "SyntaxError: expected expression, got '<' " in Firefox with the following code:

Node.js route:

app.get("/testpage", function(req, res){

  var theObject = {
  id: 123,
  name: "Bob"
  }

  res.render("testpage", {objectFromNode: theObject});
});

My javascript file (myjavascriptfile.js):

var myObj= <%-JSON.stringify(objectFromNode)%>
console.log(myObj);

HTML (testpage.ejs):

<html>
  <head>
    <title>

    </title>
    <script src="../public/js/myjavascriptfile.js"></script>
  </head>

  <body>
    <h1>Test Page</h1>
  </body>
</html>

When I place the javascript within the script tags on the page itself then everything works as needed.

Does anyone have an idea on why this is happening and how to fix it?

1 Answers

0
tevemadar On

You would have to "render" the JavaScript file too. As I do not know neither routing, nor ejs, I can only mimic something based off your code:

app.get("/js/myjavascriptfile.js", function(req, res){

  var theObject = {
    id: 123,
    name: "Bob"
  }

  res.render("testjavascriptfile", {objectFromNode: theObject});
});

Where testjavascriptfile.ejs would be the JS code with the ejs tag:

var myObj= <%-JSON.stringify(objectFromNode)%>
console.log(myObj);