Javascript 如何在浏览器中以某种格式显示数据库内容?
My node.js代码:Javascript 如何在浏览器中以某种格式显示数据库内容?,javascript,mysql,node.js,Javascript,Mysql,Node.js,My node.js代码: http.createServer(function (request, response) { console.log('Creating the http server'); connection.query('SELECT * FROM navd_compare LIMIT 100', function(err, rows, fields) { console.log('Connection result error '+e
http.createServer(function (request, response)
{
console.log('Creating the http server');
connection.query('SELECT * FROM navd_compare LIMIT 100', function(err, rows, fields)
{
console.log('Connection result error '+err);
console.log('no of records is '+rows.length);
response.writeHead(200, { 'Content-Type': 'application/json'});
response.end(JSON.stringify(rows));
response.end();
});
}).listen(8084);
如果要在服务器上编写最少的代码,可以使用Express。例如:
var app = express();
app.route('/data')
.get(function(req, res, next) {
/*your sql query*/
res.json(result);
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
之后,您可以使用AJAX在客户机上请求路由。以下是Fetch API的一个示例:
有什么问题吗?首先不要使用.end twicewhere/how定义连接?在浏览器中我得到JSON输出,但我希望它在表中。如何从数据库中检索每行数据?并将其转换为js对象并在browservar http=require'http'中打印;var mysql=require'mysql';var connection=mysql.createConnection{host:'localhost',user:'root',password:'tas123',database:'navd'};连接只需使用任何视图引擎,如ejs、jade或handle bar即可
fetch("http://localhost:3000/data").then(r => r.json()).then(data => {
/* here is your data */
})