var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');//解析,用req.body获取post参数
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//设置跨域访问
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
//连接数据库
var connection = mysql.createConnection({
host: 'localhost',//主机
user: 'root',//mysql认证的用户名
password: '123456',//mysql用户密码
database: 'test',//数据库名
port: '3306'//端口号
});
connection.connect();
var questions = [
{
data: 213,
num: 444,
age: 12
}
];
//列表
app.get('/list', function (req, res) {
var sql = 'SELECT * FROM hello';
connection.query(sql, function (err, result) {
if (err) {
console.log('[SELECT ERROR] - ', err.message);
return;
}
res.json(result)
});
});
//新增插入
app.get('/list_add', function (req, res) {
var addSql = 'INSERT INTO hello(name) VALUES(?)';
var addSqlParams = req.query.name;
connection.query(addSql, addSqlParams, function (err, result) {
if (err) {
console.log('[INSERT ERROR] - ', err.message);
return;
}
res.json({ success: '添加成功' })
});
});
//修改
app.get('/list_edit', function (req, res) {
var modSql = 'UPDATE hello SET name = ? WHERE Id = ?';
var modSqlParams = [req.query.edit, req.query.id];
//改
connection.query(modSql, modSqlParams, function (err, result) {
if (err) {
console.log('[UPDATE ERROR] - ', err.message);
return;
}
res.json({ success: '修改成功' })
});
});
//删除
app.get('/list_del', function (req, res) {
var delSql = "DELETE FROM hello WHERE Id = ?"
//删
var delid = [req.query.id];
connection.query(delSql, delid, function (err, result) {
if (err) {
console.log('[DELETE ERROR] - ', err.message);
return;
}
res.json({ success: '删除成功' })
});
// console.log("主页 POST 请求");
// res.send('Hello POST');
})
//登录接口
app.get('/user', function (req, res) {
res.status(200),
res.json(questions)
});
//post接口 获取参数req.body
app.post('/demo', function (req, res) {
// console.log("主页 POST 请求");
var delSql = "DELETE FROM hello WHERE Id = ?"
var delid = [req.body.id];
// console.log(req.body.id)
connection.query(delSql, delid, function (err, result) {
if (err) {
console.log('[SELECT ERROR] - ', err.message);
return;
}
res.json(result)
});
})
//配置服务端口
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
})