I'm looking for a way to render a view that will have a variable containing data fetched from the API. I'm using express, handlebars and request.
Here's the web-server's router code:
const express = require('express');
const router = express.Router();
const request = require('request');
router.get('/projects', (req, res) => {
request('http://localhost:8080/NpZke93tNYf9eR07fIDm/reports/projects', (error, response, body) => {
res.render('projectsPage', {projects: JSON.stringify(response.body)});
})
});
// returns:
// {"data":[{"project":"project 1","details":"details of project 1"},{"project":"project 2","details":"some other details"}],"message":"ok","code":200}
And here's the handlebars view's code (projectsPage.hbs):
<h1>Available Projects</h1>
<script>
var myData = "{{projects}}";
</script>
The problem is that my when the view's rendered, the myData variable contains content that canot be parsed by JSON.parse().
>myVar
""{"data":[{"project":"project 1","details":"details of project 1"},{"project":"project 2","details":"some other details"}],"message":"ok","code":200}""
What I'm trying to do is to render a page which will present the data using Chart.js (that's why I need to have the data available as an object). I don't want to make direct calls to the API from the front-end (to not expose api key).
Is there a way to make it work without having to use String.replace() method? Is my approach valid or is there a better way to do this?
Change
<h1>Available Projects</h1>
<script>
var myData = "{{projects}}";
</script>
to
<h1>Available Projects</h1>
<script>
var myData = {{{projects}}}
</script>
When you are creating Chart instance on Javascript, use the following:
data: JSON.parse(myData),
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.