我完成了从数据库中获取数据并存储在我的节点js文件中的对象中,但我无法将该对象发送到我的克林特JavaScript文件中。
我尝试了2-3种方式,但我无法在JavaScript文件中访问我的对象;是的,我不想通过.ejs文件来做,我必须在javascript文件中对'data'进行一些操作。
app.post('/submit-rowmatrial', (req, res) => {
const connection = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'mydb'
});
app.get('/:id', (req, res) => {
const tagId = req.params.id;
// console.log(tagId)
if (tagId !== 'manage-stock') return;
const sql = 'select itam_name,sum(quantity) as value_sum from raw_materials group by itam_name';
let connection = create_conection();
connection.query(sql, (err, result) => {
if (err) throw err;
// store the result in a variable
data = result;
connection.end((err) => {
if (err) throw err;
console.log('Connection closed!');
});
res.json(data);
});
});
〉!现在我正在尝试获取javascript文件中的数据
fetch('http://localhost:3002/manage-stock')
.then(response => response.json())
.then(data => {
console.log(data);
for(let i=0; i<data.length; i++){
let ob = data[i];
let values = Object.values(ob);
iteam_name=values[0];
quantity=values[1];
console.log(iteam_name+" -> "+quantity);
}
})
1条答案
按热度按时间toiithl61#
在代码中做一些修改
这是第一部分。这里连接变量仅限于第一个app.post()回调。
处理数据库连接的一个更好的方法是创建一个单独的全局变量,或者从一个完全不同的模块中导出它。此外,创建一个新的连接池,而不仅仅是一个连接,它会为每个查询重复连接和断开连接。
使用此数据库对象进行查询。
现在,在代码的第二部分,其中
app.get('/:id')
if (tagId !== 'manage-stock') return;
,即使你想退出函数,你也需要返回一些数据给客户端,否则客户端将永远等待。因此相反,
然后继续其余的代码。
const sql = 'select itam_name,sum(quantity) as value_sum from raw_materials group by itam_name';
使用
db
对象执行查询