如何将JavaScript对象/数组发送到前端-Node.js应用

时间:2019-05-16 14:59:42

标签: javascript html mysql node.js response

我正在尝试将数据发送到应用程序的前端以创建图形。我将数组附加到响应对象中,但这不起作用,尽管我可以使用也在前端响应对象中发送的用户值。

var scoreQuery = "SELECT q1, q2, q3, q4, q5, q6, q7, q8, q1, q2, q3, q4 FROM table WHERE id = user.id";

var scoreArray;

module.exports = function(app, passport){

    app.get('/profile', isLoggedIn, function (req, res) {
        connection.query(scoreQuery, function (err, result, fields) {
                if (err) throw err;
                getData(result);
                console.log(scoreArray);
            }, res.render('profile.ejs', {
                user:req.user,
                data: scoreArray
            })
        );


    });

};

function getData(result){
    Object.keys(result).forEach(function(key) {
        const values = result[key];
        scoreArray = Object.values(values);
    });
});

下面是我创建图表的public / javascripts / scripts.js文件。

/*Scripts*/

var quizCategory1 = data.scoreArray.slice(0,7); 
var quizCategory2 = data.scoreArray.slice(8,11);

var cat1Total = totalScore(category1);
var cat2Total = totalScore(category2);


function totalScore(categoryScore){
    return categoryScore = scoreArray.reduce((accum,scoreArray) =>
        {
            const splitValues = scoreArray.split('/');

            return {
                score:accum.score + parseInt(splitValues[0]),
                maxScore:accum.maxScore + parseInt(splitValues[1]),
            }
        },{score:0,maxScore:0}
    );
}


var ctx = document.getElementById("myChart").getContext('2d');
var barTotalCategoryScores = [cat1Total.score, cat2Total.score];

var labels = ["Java & Design", "Build & Versioning"];

var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: labels,
        datasets: barTotalCategoryScores
          }
    }
});

每当用户登录时,scoreArray就会输出到控制台,以便sql query和getData()函数正常工作。但是,当我尝试在我的scripts.js文件中使用data.scoreArray时,它就无法工作。

3 个答案:

答案 0 :(得分:1)

添加新路线:

app.get('/profile/:id', (req,res) => {
    // your_array = query DB with param id (req.params.id) store in your array
    res.status(200).json({data: <your_array>})
})

然后在您的客户端上对/ profile /:id(https://developer.mozilla.org/fr/docs/Web/API/XMLHttpRequest)进行GET查询 页面加载时(window.onload)


对于MySQL,您应该使用:

答案 1 :(得分:1)

服务器:


// ... your routes


// + new route
app.get('/profile/:id', (req,res) => {
     let id = req.params.id // e.g /profile/3 -> req.params.id = 3
     let scoreArray;

     // your query (it's very bad to set param in your query like this (injection SQL) )
     let scoreQuery = `SELECT q1, q2, q3, q4, q5, q6, q7, q8, q1, q2, q3, q4 FROM 
     table WHERE id = ${id}`;  // `... ${foo}` => https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Litt%C3%A9raux_gabarits

     connection.query(scoreQuery, function (err, result, fields) {
                if (err) throw err;
                getData(result);
                console.log(scoreArray);
             }, res.status(200).json({
                user:req.user,
                data: scoreArray
            })
        );
 })

// ... your method

function getData(result){
    Object.keys(result).forEach(function(key) {
        const values = result[key];
        scoreArray = Object.values(values);
    });
});

客户端:

/* code to get data
 let id_test = 1;

  fetch(`http://localhost:<your_node_server_port>/profil/${id_test}`)
  .then(response => response.json())
  .then(json => console.log(json)) // return profil for id 1
*/

// e.g page is loaded
window.onload = () => {
  let id_test = 1;

  fetch(`http://localhost:<your_node_server_port>/profil/${id_test}`)
  .then(response => response.json())
  .then(json => console.log(json)) // return profil for id 1
}

答案 2 :(得分:0)

感谢一百万西尔万,您的解释使我走上了正确的轨道。我做了以下...

//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,并发送id参数作为值插入查询方法中。这已经奏效了,现在我可以使用<?= score.cat1Total.score ?>在客户端ejs文件上获取score对象。

我的问题现在仍在尝试在我的public / javascripts / scripts.js文件中使用score.cat1Total.score,并且它是未定义的...而且我不确定如何正确实现您的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);

        });
    })
}