node+express实现简单的增删改查
var express = require('express'); var bodyParser = require("body-parser"); var cors = require('cors'); var app = express(); var mysql = require('mysql'); var connection = mysql.createPool({ connectionLimit : 10, host : 'localhost', user : 'root', //数据库登陆就名 password : '123321', //数据库登陆密码 database : 'test1' //数据库名 }); app.use(cors()); //跨域处理 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); //查询user app.get('/listUsers', function (req, res) { connection.query('select * from `userone`', function(err, rows, fields) { if (err) throw err; var data = {code:'200',code_decoration:'查询成功'}; data.order = rows; res.send(data); }) }); //增加user app.post('/adduser', function(req, res){ console.log(req.body); var param = req.body || req.params; connection.query('insert into userone(id, name, password, email) values(0,?,?,?)', [param.name,param.password,param.email], function(err, result) { if (err){ throw err; }else{ var data = {code:'200',code_decoration:'添加成功'}; res.send(data); } }); }); //删出user app.post('/delUser', function (req, res) { var name = req.body.name || req.params.name; console.log(name); connection.query("delete from userone where name=" + name, function (err, rows) { if (err) { res.send('删除失败:' + err); } else { var data = {code:'200',code_decoration:'删除成功'}; res.send(data); } }); }); //update user app.post('/updateUser', function (req, res) { var param = req.body || req.params; console.log(param.name + '--' +param.password); connection.query("update userone set password=" + param.password + 'where name=' + param.name, function (err, rows) { if (err) { res.send('更新失败:' + err); } else { var data = {code:'200',code_decoration:'更新成功'}; res.send(data); } }); }); var server = app.listen(8081, function () { console.log("服务启动成功!"); })
本文来自博客园,作者:_zhiqiu,转载请注明原文链接:https://www.cnblogs.com/guojikun/p/6535648.html