javascript - 如何将 JavaScript 对象/数组发送到前端 - node.js 应用程序

标签 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 查询和 getData() 函数正常工作。但是当我尝试在 script.js 文件中使用 data.scoreArray 时,它不起作用。

最佳答案

服务器:


// ... 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
}

关于javascript - 如何将 JavaScript 对象/数组发送到前端 - node.js 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56171480/

相关文章:

mysql - 将列数据复制到另一列的正确mysql语法是什么

javascript - <option>标签,显示:none and jquery

javascript - Gmaps4Rails - 入门

javascript - 为什么使用带有 javascript : "protocol"? 的链接是不好的做法

html - 纯 SVG Javascript 库

mysql - 使用不一致的列名加载 XML LOCAL INFILE

php - mysql 和 php 搜索突出显示

javascript - HTML5 视频图像/海报淡入淡出

javascript - 如何为 html 元素的填充设置动画

html - 使用单一 html 结构的同一域的双语(英语和阿拉伯语)网站?