0

Im fetching data on my server from a exteranal API, then im trying to send that data to an ejs file using JSON.stringify(data), and trying to read the data in the ejs file with JSON.parse(data), but im either getting something like [Object object] or a string with a lot of weird characters in it, i tried using replace, but it still doesnt work.

This is what i have on the server side.

router.get("/api", (req, res) => {

const info = {
        place: "London",
        country: "UK",
        temp: "16",
        weather: "Cloudy",
      };
      res.render("weathery", { user: JSON.stringify(info) });
}

This is what i have on the ejs file side.

<script>
      var data = "<%= user %>";
      const newData = data;

      console.log(newData);
</script>

This is what it prints without using JSON.parse

{"place":"London","country":"UK","temp":"16","weather":"Cloudy"}

i tried using replace on the weird characters like #,&,; and 34 and it didnt work, also that would lead to a problem on some cases if was receving some data with the number 34

Whenever i tried to parsed it send an error "Uncaught SyntaxError: Unexpected token & in JSON at position 1"

Hopefully you can help me, have a nice day :)

CinemaClub
  • 69
  • 6
  • Does this answer your question? [Express and ejs <%= to render a JSON](https://stackoverflow.com/questions/13788314/express-and-ejs-to-render-a-json) – Krzysztof Krzeszewski Apr 25 '22 at 13:22
  • 1. `res.render("weathery", { info });` 2. `const data = <%= info %>;` 3. `console.log(data);` (your problem are the quotes; inserting JSON into a script produces an object literal which is already fine as-is. Wrapping it in quotes will mess up the syntax (since JSON uses the same quotes as delimiters) and next the JSON string has to also be parsed back into an object. This is unnecessary. JSON is short for "JavaScript Object Notation" and that's exactly what it is. –  Apr 25 '22 at 13:38
  • Thank you for your answer, the thing is whenever i try to get the quotations out of the "<%= user%>" the script will send up an error, so i still have the issue on how to access that data on the script, since i where i need to program the logic – CinemaClub Apr 25 '22 at 13:50
  • If you're getting an error, please state the error message... –  Apr 25 '22 at 14:03
  • Note that since your ultimate goal is to request data from your server, you might want to do `res.json(info);` instead of rendering a template, then fetch() that in your client-side script. You can use `fetch('/api').then(r => r.json()).then(info => { console.log(info); });` to do that –  Apr 25 '22 at 14:05
  • This is the error im getting "Uncaught SyntaxError: Unexpected identifier (at api:17:26)" ``` ``` ``` – CinemaClub Apr 25 '22 at 14:10

1 Answers1

0

Change this

var data = "<%= user %>"

To this:

var data = `<%- user %>`
Aimsat
  • 338
  • 4
  • 10