Node 一个简单的HttpServer+Mysql的后台

接收来自客户端的Post参数,通过Mysql查询,并以Json返回需要的信息,直接代码

createServer();

function createServer(){
	//使用express创建HTTP服务器
	var express = require('express');
	var bodyParser = require('body-parser');
	var app = express();
	var server = require('http').createServer(app);
	var PORT = process.env.PORT || 8002;
	server.listen(PORT);
	console.log('Server running.');

	//连接mysql
	var mysql = require('mysql');
	var conn = mysql.createConnection({
	    host: 'localhost',
	    user: 'root',
	    password: 'root',
	    database:'NodeDB',
	    port: 8889
	});
	conn.connect();
	console.log("Connect Mysql Success");

	// conn.end();
	setupRoute();
	//设定路由
	function setupRoute(){
		//使用body-parser解析body参数
		app.use(bodyParser.urlencoded({   
  			extended: true
		}));

		app.get('/getdemo', function (req, res) { 
			res.contentType('json');//返回的数据类型
			console.log("Get method");
			// console.log(req.query); 
			var selectSQL = 'SELECT * from UserTB where account = "'+req.query.account+'"';
			//select
			conn.query(selectSQL, function (err, rows) {
			 	if (err) console.log(err);
				console.log("SELECT ==> ");
			    for (var i in rows) {
			    	console.log(rows[i]);
			    	res.send(JSON.stringify(rows[i]));//给客户端返回一个json格式的数据
			    }
			});
		}); 

		app.post('/postdemo', function (req, res) { 
			res.contentType('json');//返回的数据类型
			console.log("Post method");
			console.log(req.body); 
			var selectSQL = 'SELECT * from UserTB where account = "'+req.body.account+'"';
			//select
			conn.query(selectSQL, function (err, rows) {
			 	if (err) console.log(err);
				console.log("SELECT ==> ");
			    for (var i in rows) {
			    	console.log(rows[i]);
			    	res.send(JSON.stringify(rows[i]));//给客户端返回一个json格式的数据
			    }
			}); 
		}); 
	}
}

 

posted @ 2015-11-27 09:32  Rayshen  阅读(444)  评论(0编辑  收藏  举报