1、使用mysql 模块和 HTTP模块
//those code is aim to create a server by using http mode and connet to mysql database
const http = require("http");
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database : 'webui'
});
const server = http.createServer((req,res)=>{ //create a sever
console.log('request!');
queryUser(req,res);//do function
});
server.listen(3000,err=>{
if(err){
console.log('server error');
}else{
console.log('server stated.....');
}
})
console.log('Server running at http://127.0.0.1:3000/');
function queryUser(req,res){
connection.query('select * from users',(err,result)=>{
if(err){
res.statusCode = 500;
res.write('db error');
res.end();
}else{
res.statusCode = 200;
res.setHeader('content-type','application/json');
console.log(result);
res.write(JSON.stringify(result));
res.end();
}
})
}