gpt4 book ai didi

mysql - NodeJS 在浏览器中输出用户

转载 作者:搜寻专家 更新时间:2023-10-30 23:30:42 26 4
gpt4 key购买 nike

我做了一个项目,其中包含我在 mysql 上编写的数据库,它从数据库中生成一个 json 文件,并在浏览器中输出所有用户,但我遇到了一些问题。我想输出一个用户我该怎么做(这是示例它必须如何输出 http://localhost:8080/user/1)。我使用了 express 和 mysql。请帮我。谢谢。

这是我的代码:

'use strict';
const mysql = require('mysql');
const express = require('express');
const http = require('http');
const router = express()

// http://nodejs.org/docs/v0.6.5/api/fs.html#fs.writeFile
const fs = require('fs');

const connection = mysql.createConnection({
host: 'localhost',
user: 'lado',
password: '1234'
});

connection.connect();

connection.query('SELECT * FROM bankdb.account;', function(err, results, fields) {
if(err) throw err;

fs.writeFile('account.json', JSON.stringify(results), function (err) {
if (err) throw err;
console.log('Saved!');
});
connection.end();
});


const pool = mysql.createPool({
host: 'localhost',
user: 'lado',
password: '1234',
database: 'bankdb',
charset: 'utf8'
});
var reo ='<html><head><title>Output From MYSQL</title></head><body><h1>Output From MYSQL</h1>{${table}}</body></html>';
function setResHtml(sql, cb){
pool.getConnection((err, con)=>{
if(err) throw err;

con.query(sql, (err, res, cols)=>{
if(err) throw err;

var table =''; //to store html table

//create html table with data from res.
for(var i=0; i<res.length; i++){
table +='<tr><td>' + (i+1) +'</td><td>'+ res[i].name +'</td><td>'+ res[i].address +'</td></tr>';
}
table ='<table border="1"><tr><th>ID</th><th>Name</th><th>Amount</th></tr>'+ table +'</table>';

con.release(); //Done with mysql connection

return cb(table);
});
});
}

const sqll ='SELECT * FROM bankdb.account';

const server = http.createServer((req, res)=>{
setResHtml(sqll, resql=>{
reo = reo.replace('{${table}}', resql);
res.writeHead(200, {'Content-Type':'text/html; charset=utf-8'});
res.write(reo, 'utf-8');
res.end();
});
});

server.listen(8080, ()=>{
console.log('Server running at //localhost:8080/');
router.get('/users/:id', function(req, res, next) {
var user = users.getUserById(req.params.id);
res.json(user);
});
exports.getUserById = function(id) {
for (var i = 0; i < users.length; i++) {
if (users[i].id == id) return users[i];
}
};
});

最佳答案

只需根据他们的 id 获取特定用户:

router.get( '/user/:id', function( req, res ) { // When visiting '/user/:id'

var id = req.params.id; // For example if you visit localhost/user/24 the id will be 24

connection.query('SELECT * FROM bankdb.account WHERE id=' + mysql.escape( id ), function(err, results, fields) {
if(err) throw err;

fs.writeFile('account.json', JSON.stringify(results), function (err) {
if (err) throw err;
console.log('Saved!');
});
connection.end();
});

} );

如果您从数据库中获取每个用户,您的程序将占用更多内存。

只需捕获您需要的那个并与他一起工作。

关于mysql - NodeJS 在浏览器中输出用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49473918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com