Спасибо миллиону Сильвен, твое объяснение привело меня на правильный путь.Я сделал следующее ...
//routes.js
app.get('/profile', function (req, res) {
let id = req.user.id;
getData(id, function (score) {
res.status(200).render('profile.ejs',{user: req.user, score})
});
});
Я поместил свой SQL-оператор в функцию getData()
и использовал '?'
вместо идентификатора в моем SQL-операторе и отправил параметр id в качестве значения для вставки вметод запроса.Это сработало, и теперь я могу получить объект счета в файле ejs на стороне клиента, используя <?= score.cat1Total.score ?>
.
. Моя проблема сейчас все еще пытается использовать score.cat1Total.score
в моем public / javascripts / scripts.jsфайл и он не определен ... и я не уверен, как правильно реализовать ваш window.onload()
метод
// /public/javascripts/scripts.js
/* code to get data?
window.onload = () => {
fetch(`http://localhost:8080/profile)
.then(response => response.json())
.then(json => console.log(json))
}
*/
var ctx = document.getElementById("myChart").getContext('2d');
//This is where I am trying to get score objects values.
var barTotalCategoryScores = [score.cat1Total.score, cat2Total.score];
var labels = ["Java & Design", "Build & Versioning"];
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: barTotalCategoryScores
}
}
});
Для справки ниже приведен метод getData(id, callback)
, который я использовал в маршрутах
// routes.js
function getData(id, callback) {
let scoreQuery = "SELECT c1q1, c1q2, c1q3, c1q4, c1q5, c1q6, c1q7, c1q8, c2q1, c2q2, c2q3, c2q4 FROM nodejs_login.assessment_score AS a JOIN nodejs_login.users as u ON a.respondent_id = u.user_respondent_id WHERE a.respondent_id = ?";
connection.query(scoreQuery, [id],function (err, result) {
if (err) throw err;
Object.keys(result).forEach(function(key) {
let values = result[key];
let scoreArray = Object.values(values);
let category1 = scoreArray.slice(0,7);
let category2 = scoreArray.slice(8,11);
//parsing and accumlating each category score
var cat1Total = totalScore(category1);
var cat2Total = totalScore(category2);
//function to parse the strings into numbers and accumulate them
function totalScore(categoryScore){
return categoryScore.reduce((accum,scoreArray) =>
{
const splitValues = scoreArray.split('/');
return {
score:accum.score + parseInt(splitValues[0]),
maxScore:accum.maxScore + parseInt(splitValues[1]),
}
},{score:0,maxScore:0}
);
}
let categories = {cat1Total, cat2Total};
callback(categories);
});
})
}