javascript - 如何在节点js中将数据库与浏览器连接?
问题描述
这是我的代码:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "123",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT users.name AS user, products.name AS favorite FROM users JOIN products ON users.favorite_product = products.id";
con.query(sql, function (err, result) {
if (err) throw err;
console.log('hello world');
});
});
}).listen(8080);
解决方案
您需要将 sql 查询传递到 nodejs Web 服务器,然后将结果作为响应。
var http = require('http');
var url = require('url');
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "123",
database: "mydb"
});
http.createServer(function (req, res) {
var query = url.parse(request.url, true).query;
res.writeHead(200, {'Content-Type': 'text/html'});
con.connect(function(err) {
if (err) throw err;
var sql = unescape(query.sql);
con.query(sql, function (err, result) {
if (err) throw err;
res.end(JSON.stringify(result));
});
});
}).listen(8080);
然后你就打电话
var sql = escape("select * from table")
http://localhost:8080/?sql=select%20 *%20from%20table
推荐阅读
- java - 休眠性能不佳
- mongodb - Mongodump数据库备份错误如何解决?
- php - 使用自动 URL 在代理下执行 php 命令。
- powershell - 从 Shell 脚本管道命令到 PowerShell
- javascript - 使用 Rubaxa Sortable 使用 AJAX 更新数据库
- python - Python 类方法 - 适当的静态与实例使用
- python - fcm django,向拥有多个设备的单个用户发送消息
- html - 通过 innerHTML 输入时 span 不应用 css 样式
- visual-studio-2017 - VS 2017 深色主题更改
- kernel - yocto 上的 ADV7513 - 内核 4.14