操作mysql数据库
在server文件夹新建一个sql.js连接数据库
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password: '密码',
database: 'shop'
})
module.exports = connection;
在index.js文件中操作mysql数据库
前台通过url传值
对数据库的操作
var express = require('express');
var router = express.Router();
var connection = require('../db/sql.js')
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
//对数据库的操作
router.get('/api/goods',function(req, res, next) {
//desc降序 asc升序
//获取对象的key
let [goodsName,orderName] = Object.keys(req.query);
let name = req.query.name;
let order = req.query[orderName];
connection.query("select * from shopdata where name like '%"+name+"%' order by "+orderName+" "+order+" ", function (error,results,fields) {
if(error) throw error;
// console.log(results);
res.send({
code:"0",
data:results
})
});
});