I'm retrieving data from an external API on my server, then attempting to pass that data to an ejs file using JSON.stringify(data), and trying to read the data in the ejs file by parsing it with JSON.parse(data). However, I am encountering issues where I either receive something like [Object object] or a string filled with strange characters. I have even tried using the replace method, but it still doesn't seem to resolve the problem.
Here is an example of 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) });
}
And here is what I have on the ejs file side:
<script>
var data = "<%= user %>";
const newData = data;
console.log(newData);
</script>
When printing without using JSON.parse, this is the result:
{"place":"London","country":"UK","temp":"16","weather":"Cloudy"}
I attempted replacing special characters like #, &, ;, and 34, but it didn't work. Additionally, this could cause problems if the data includes the number 34 in some cases.
Every time I try to parse the data, I receive the following error message: "Uncaught SyntaxError: Unexpected token & in JSON at position 1"
If you can provide assistance, I would greatly appreciate it. Have a wonderful day! :)