1.安装生成器
npm install express-generator -g
2. 创建名称为APP的应用:
express my-project
3.安装依赖包
cd my-project
npm install
4、启动应用
npm start
5、在浏览器中使用 localhost:3000访问
默认的端口就是3000
更改端口:
路径:app/bin/www
var port = normalizePort(process.env.PORT || '3000');
6、设置请求跨域头
// app.js app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "http://localhost:3000"); res.header("Access-Control-Allow-Origin", "http://localhost:8080"); res.header("Access-Control-Allow-Origin", "http://127.0.0.1:8080"); // res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); next(); });
注:该模板默认用的是 .jade 文件作为模板渲染 若要使用 ejs 可按照一下方法配置
1、安装 ejs
npm install ejs -S
2、在app.js中添加一下代码
var ejs = require('ejs'); app.engine('.html', ejs.__express); app.set('view engine', 'html');
3、将view文件夹中的模板替换成 .html 文件即可(每次配置一个路由需要重新启动一下服务器)
参考文档:
https://www.jianshu.com/p/b555ba6f4067
mysql数据库配置
1、安装mysql
npm install mysql -S
2、建立对应的文件
//mysql.js // MySQL数据库联接配置封裝 var mysql = { host: '127.0.0.1', user: 'root', password: 'tll456456', database: 'test', port: 3306 }; module.exports = mysql;
//handel.js /* 数据增删改查模块封装 req.query 解析GET请求中的参数 包含在路由中每个查询字符串参数属性的对象,如果没有则为{} req.params 包含映射到指定的路线“参数”属性的对象,如果有route/user/:name,那么“name”属性可作为req.params.name req.body通常用来解析POST请求中的数据 +req.query.id 可以将id转为整数 */ // 引入mysql var mysql = require('mysql'); // 引入mysql连接配置 var mysqlconfig = require('../config/mysql'); // 引入连接池配置 var poolextend = require('./poolextend'); // 引入SQL模块 var sql = require('./sql'); // 引入json模块 var json = require('./json'); // 使用连接池,提升性能 var pool = mysql.createPool(poolextend({}, mysqlconfig)); var userData = { add: function(req, res, next) { pool.getConnection(function(err, connection) { var param = req.query || req.params; connection.query(sql.insert, [param.id, param.name, param.age], function(err, result) { if (result) { result = 'add' } // 以json形式,把操作结果返回给前台页面 json(res, result); // 释放连接 connection.release(); }); }); }, delete: function(req, res, next) { pool.getConnection(function(err, connection) { var id = +req.query.id; connection.query(sql.delete, id, function(err, result) { if (result.affectedRows > 0) { result = 'delete'; } else { result = undefined; } json(res, result); connection.release(); }); }); }, update: function(req, res, next) { var param = req.body; if (param.name == null || param.age == null || param.id == null) { json(res, undefined); return; } pool.getConnection(function(err, connection) { connection.query(sql.update, [param.name, param.age, +param.id], function(err, result) { if (result.affectedRows > 0) { result = 'update' } else { result = undefined; } json(res, result); connection.release(); }); }); }, queryById: function(req, res, next) { var id = +req.query.id; pool.getConnection(function(err, connection) { connection.query(sql.queryById, id, function(err, result) { if (result != '') { var _result = result; result = { result: 'select', data: _result } } else { result = undefined; } json(res, result); connection.release(); }); }); }, queryAll: function(req, res, next) { pool.getConnection(function(err, connection) { connection.query(sql.queryAll, function(err, result) { if (result != '') { var _result = result; result = { result: 'selectall', data: _result } } else { result = undefined; } json(res, result); connection.release(); }); }); } }; module.exports = userData;
//json.js //封装接送模块 var json = function(res, result) { if (typeof result === 'undefined') { res.json({ code: '1', msg: '操作失败' }); } else if (result === 'add') { res.json({ code: '200', msg: '添加成功' }); } else if (result === 'delete') { res.json({ code: '200', msg: '删除成功' }); } else if (result === 'update') { res.json({ code: '200', msg: '更改成功' }); } else if (result.result != 'undefined' && result.result === 'select') { res.json({ code: '200', msg: '查找成功', data: result.data }); } else if (result.result != 'undefined' && result.result === 'selectall') { res.json({ code: '200', msg: '全部查找成功', data: result.data }); } else { res.json(result); } }; module.exports = json;
//poolextent.js // 连接池扩展封装 var poolextend = function(target, source, flag) { for (var key in source) { if (source.hasOwnProperty(key)) { flag ? (target[key] = source[key]) : (target[key] === void 0 && (target[key] = source[key])); } } return target; } module.exports = poolextend;
//sql.js // SQL语句封裝 var user = { insert:'INSERT INTO user(id, name, age) VALUES(?,?,?)', update:'UPDATE user SET name=?, age=? WHERE id=?', delete: 'DELETE FROM user WHERE id=?', queryById: 'SELECT * FROM user WHERE id=?', queryAll: 'SELECT * FROM user' }; module.exports = user;
//router/index.js var express = require('express'); var router = express.Router(); var user = require('../modules/handle'); /* GET users listing. */ router.get('/', function(req, res, next) { res.render('index', { title: 'SQL for MySQL' }); }); router.get('/addUser', function(req, res, next) { user.add(req, res, next); }); router.get('/queryAll', function(req, res, next) { user.queryAll(req, res, next); }); router.get('/query', function(req, res, next) { user.queryById(req, res, next); }); router.get('/deleteUser', function(req, res, next) { user.delete(req, res, next); }); router.get('/update', function(req, res, next) { res.render('update'); }); router.post('/updateUser', function(req, res, next) { user.update(req, res, next); }); module.exports = router;
//index.jade extends layout block content h1= title p a(class={active: currentUrl === '/'} href='/queryAll') 数据查询 p a(class={active: currentUrl === '/'} href='/query?id=1') 定向查询 p a(class={active: currentUrl === '/'} href='/addUser?id=0&name=xyz&age=18') 数据插入 p a(class={active: currentUrl === '/'} href='/update') 数据更新 p a(class={active: currentUrl === '/'} href='/deleteUser?id=0') 数据删除 p
//layout.jade doctype html html head title= title link(rel='stylesheet', href='/stylesheets/style.css') body block content
//update.jade extends layout block content h1 更新用户资料 form(method='post', action='updateUser') div.form-row label span ID: input(type='text',name='id') div.form-row label span name: input(type='text',name='name') div.form-row label span age: input(type='text',name='age') div.form-row input(type='submit')