node代码实现
```node var http = require("http"); var fs = require("fs"); var url = require("url"); var mysql = require("mysql");http.createServer(function(request, response) {
var connection = mysql.createConnection({
host : "localhost",
post : 3000,
user : "",
password : "",
database : "123"
});
var pathname = url.parse(request.url).pathname;
var ext = pathname.match(/(.[^.]+|)$/)[0]; //取得后缀名
switch (ext) {
case ".css":
case ".js":
case ".png":
case ".jpg":
fs.readFile("." + request.url, function(err, data) {
response.writeHead(200, {
"Content-Type": {
".css": "text/css",
".js": "application/javascript",
".jpg": "image/jpeg",
".png": "image/png",
}[ext]
});
response.end(data);
});
break;
default:
if(request.url == "/login"){
connection.query("SELECT * FROM login
", function(error, results) {
if(error) {
console.log("login error");
} else {
var loginobj = {
success : true,
information : results
};
response.end(JSON.stringify(loginobj));
}
});
}
else if(request.url == "/lotteryPeople") {
connection.query("SELECT * FROM lotteryPeople
", function(error, results)
{
if(error) {
console.log("lottey error");
} else {
var lotteryPeopleobj = {
success : true,
lotteryP : results
};
response.end(JSON.stringify(lotteryPeopleobj));
}
});
}
else {
fs.readFile("./index.html", "utf-8", function(err,data) {
if (err) throw err;
//response.write();
response.writeHead(200, {
"Content-Type": "text/html",
});
response.end(data);
});
}
}
//connection.end();
}) .listen(3000);
console.log("server start...");
<div style="font-size:14px">注释:创建用户给权限从服务器的123数据库上取得login和lotteryPeople两张表上的数据返回给前端,这里我只实现了从服务器取数据给前端ajax接口接收,在前端ajax接口接收url分别写"http://xxx:3000/login"和"http://xxx:3000/lotteryPeople"即可。</div>