首页 > 解决方案 > 如何在节点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);

标签: javascriptnode.jshtml

解决方案


您需要将 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


推荐阅读