//全局Express框架
const express = require("express");
const router = express.Router();
module.exports = router;
//加载配置文件
const config = require("../config/mysql");
const mysql = require("mysql");
const conn = mysql.createConnection(config);
//查询数据(all方法支持POST、GET、PUT、PATCH、DELETE传参方式)
router.all("/select", (req, res) => {
// 定义SQL语句
const id = req.body.id || req.query.id;
const sqlStr = "select * from user " + (id ? "where id = ?" : "");
conn.query(sqlStr, id, (err, res) => {
if (err) return res.json({code: 404, data: "获取失败"});
res.json({
code: 0, data: res
});
});
});
api/area.js(业务实现数据查询)
//全局Express框架
const express = require("express");
const router = express.Router();
module.exports = router;
//加载配置文件
const config = require("../config/mysql");
const mysql = require("mysql");
const conn = mysql.createConnection(config);
//查询数据(all方法支持POST、GET、PUT、PATCH、DELETE传参方式)
router.all("/select", (req, res) => {
// 定义SQL语句
const id = req.body.id || req.query.id;
const sqlStr = "select * from area " + (id ? "where id = ?" : "");
conn.query(sqlStr, id, (err, result) => {
if (err) return result.json({code: 404, data: "获取失败"});
res.json({
code: 0, data: result
});
});
});
config/mysql.json(数据库配置,支持mysql5.7+)
{
"host": "localhost",
"port": "3306",
"user": "root",
"password": "root",
"database": "ycapi"
}
按照上面的方式创建好项目后,记得在根目录运行:
cnpm i express & cnpm i mysql & node main
启动项目后这样访问:
http://127.0.0.1:9999/user/select
http://127.0.0.1:9999/area/select
就可以查询到数据返回的json结果了,同时也可以用POST或者GET方式传参id