mysql 我想从数据库中获取数据并显示在html文件中

w8rqjzmb  于 2023-04-05  发布在  Mysql
关注(0)|答案(1)|浏览(114)

我完成了从数据库中获取数据并存储在我的节点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);
}
})
toiithl6

toiithl61#

在代码中做一些修改

app.post('/submit-rowmatrial', (req, res) => {
  const connection = mysql.createConnection({
    host: 'localhost',
    user: 'username',
    password: 'password',
    database: 'mydb',
  });
});

这是第一部分。这里连接变量仅限于第一个app.post()回调。
处理数据库连接的一个更好的方法是创建一个单独的全局变量,或者从一个完全不同的模块中导出它。此外,创建一个新的连接池,而不仅仅是一个连接,它会为每个查询重复连接和断开连接。

const pool = mysql.createPool({
  database: 'dbName',
  password: 'root',
  host:'localhost',
  user: 'root',
});

const db = pool.promise();

使用此数据库对象进行查询。
现在,在代码的第二部分,其中app.get('/:id')
if (tagId !== 'manage-stock') return;,即使你想退出函数,你也需要返回一些数据给客户端,否则客户端将永远等待。
因此相反,

if (tagId !== 'manage-stock'){
    return res.json({
        message:'tag id is not manage-stock',
    });
};

然后继续其余的代码。
const sql = 'select itam_name,sum(quantity) as value_sum from raw_materials group by itam_name';
使用db对象执行查询

db.execute(sql)
  .then((data)=>{
     // data is an array of multiple objects along with the 
     // data fetched from the database and other related metadata.
     // the actual table data is present as the first element of data array
     // you can always console.log(data) to get a glimpse of what it is
     // returning.
     console.log(data);
     console.log(data[0]);
     return res.json(data[0]);
   })
  .catch((err)=>{
    throw err;
    // however you want to handle the error
  })

相关问题