nodejs 用http服务写数据接口

 
htp.js
-----------------------------------------------
var http = require("http");
var url = require('url');
var fs = require("fs");
var i=0;
function jin(req,res){
	i++;
var pathname = url.parse(req.url).pathname;
console.log(pathname);
if(pathname == "/favicon.ico"){
	
}else{
 fs.exists("./api"+pathname+".js", function(exists){
	 console.log(exists);
	 if(exists){
	 var p = require("./api"+pathname.toString()); 

	p.get(req,res);
	 }else{
		 
		 var p = require("./api/index"); 

				p.get(req,res); 
	 }
 })
	
	

	
}


console.log("访问成功"+i);
}
http.createServer(jin).listen(8000);
console.log("开启服务");

-----------------------------------------------
./api/tr.js
-----------------------------------------------
var mysql= require("mysql");

exports.get= function(req,res){
var con = mysql.createConnection({
	host:'127.0.0.1',
	user:'root',
	password:'',
	database:'test'
	
	
	
});
con.connect();
var sql ="select * from jin_sp";
con.query(sql,function(err,data){	
console.log(data);
res.writeHead(200,{'Content-Type':'text/html;charset=UTF-8'});

var dt ={
	id:1,
	drt:data
};
res.write(JSON.stringify(dt));
res.end();
	
});

}

评论

刷新

友情链接