const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
var mysql = require('mysql');
var result="";
// 1. 创建连接
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',//连接数据库账号
password: 'root',//连接数据库密码
port:'3306',//端口
database: 'DB' // 数据名称
});
// 2. 连接数据库 打开冰箱门
connection.connect();
// 3. 执行数据操作 把大象放到冰箱
connection.query('SELECT * FROM `user`', function (error, results, fields) {
if (error) throw error;
console.log(results);
result=results;
});
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html;charset=UTF-8');
var user=JSON.stringify(result);//转换成json格式字符串
res.end(user);
});
// 4. 关闭连接 关闭冰箱门
connection.end();
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});