nodejs 用express 访问mysql 并返回数据
//express app mysql var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var mysql = require('mysql'); //连接数据库 var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'lyx117', database: 'test' }) connection.connect(); //查 var sql = 'SELECT * FROM tb1'; //增 var sql1 = 'INSERT INTO tb1 (id,name,age) VALUES (6,"TE",15)'; //删 var sql2 = 'DELETE FROM tb1 WHERE age=15' //查到tb1所有数据并返回 connection.query(sql, function (err, result) { if (err) { throw err; return; } var tb = JSON.parse(JSON.stringify(result)) // 创建 application/x-www-form-urlencoded 编码解析 var urlencodedParser = bodyParser.urlencoded({ extended: false }) // create application/json parser var jsonParser = bodyParser.json() app.get('/', function (req, res) { res.send(tb); }); app.get('/tb', function (req, res) { res.setHeader("Access-Control-Allow-Origin", "*"); res.send(tb); }); app.post('/login', urlencodedParser, function (req, res) { if (!req.body) return res.sendStatus(400) res.send('welcome, ' + req.body.username) }) app.post('/api/users', jsonParser, function (req, res) { if (!req.body) return res.sendStatus(400) // create user in req.body }) }) connection.end; var server = app.listen(8081, function () { var host = server.address().address; var port = server.address().port; console.log("address: %s, port: %d", host, port); });
另外,全局安装热部署工具 npm install -g supervisor
使用supervisor代替nodejs启动应用
这样每次修改就不用手动开启了
但是supervisor 启动会占用很大的内存,可以全局安装 hotnode