var express = require('express') , app = express(); var querystring = require('querystring'); var util = require('util'); //和数据库建立连接 var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : '123456', // port: '3306', database: 'test', }); connection.connect(); //解决跨域 app.all('*',function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With'); res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); if (req.method == 'OPTIONS') { res.send(200); } else { next(); } }); // 获取列表 app.get('/list', function (req, res) { let [addSql,addSqlParams] = ['',[]] if(req.query.type == undefined){ addSql = 'SELECT * FROM list WHERE userId=?'; addSqlParams = [req.query.userId] }else{ addSql = 'SELECT * FROM list WHERE userId=? and type=?'; addSqlParams = [req.query.userId,req.query.type] } connection.query(addSql,addSqlParams,function (err, result) { if(err){ console.log('[INSERT ERROR] - ',err.message); return; } if(result.length){ let params = { code:1, message:"成功", data:result } res.send(params) }else{ let params = { code:0, message:"暂无数据" } res.send(params) } }); }); var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("应用实例,访问地址为 http://%s:%s", host, port) })