1.在routes下面新建一个目录为mysql--mysql.js
var mysql = require('mysql');
var dbMsg = {
host : 'localhost',
user : 'root',
password : 'root',
database : '数据库名称'
}
var connection = mysql.createConnection(dbMsg);
connection.connect();
module.exports = connection;
2. 配置路由
var loginRouter = require('./routes/login');
app.use('/login', loginRouter);
3.在routes文件夹下面创建一个login.js
var express = require('express');
var URL = require('url');
var router = express.Router();
var connection = require('./mysql/mysql');
router.post('/user',function(req, res, next){
var params = {
username : req.query.username,
password : req.query.password
}
var userStr = 'select * from user_info_t where login_name=? and password=?';
var str = [params.username,params.password];
console.log(userStr)
connection.query(userStr,str,function(err,result){
if(err){
throw err;
}else{
res.send(result)
}
})
});
router.get('/', function(req, res, next) {
var user = {
name:'',
age:'',
city:''
};
var params = URL.parse(req.url, true).query;
if(params.id == '1') {
user.name = "Mr.light";
user.age = "1";
user.city = "深圳市";
} else {
user.name = "Ms.lee";
user.age = "2";
user.city = "广东市";
}
var response = {status:1,data:user};
res.send(JSON.stringify(response))
});
module.exports = router;
4.启动bin下面的www文件 node www
5.浏览器输入http://127.0.0.1:3000/login
注意:记得安装 npm install mysql 模块
至此一个接口就这样完成了,如果有疑问记得留言 源码地址:https://gitee.com/qwerdfs/NodeJS/tree/master/nodePriject