Express基本使用
Express 是一个简洁而灵活的 node.js Web应用框架, 提供一系列强大特性帮助你创建各种Web应用。Express 不对 node.js 已有的特性进行二次抽象,我们只是在它之上扩展了Web应用所需的功能。丰富的HTTP工具以及来自Connect框架的中间件随取随用,创建强健、友好的API变得快速又简单。
- 初体验
1、新建一个文件夹 2、cd 到文件夹 3、执行 npm init(目的是生成package.json文件) 4、npm install express --save
5、新建一个 app.js(作为入口文件,名字随便你取) 6、写入以下代码
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
7、终端执行 node app.js 即可运行
- 使用自动化工具生成
- 全局安装express-generator
npm install express-generator -g
- 生成项目、安装依赖、运行项目
express myapp //在你敲命令行文件夹下面生成 myapp项目
cd 到myapp文件夹
npm install //安装依赖
npm run start //运行项目
- 模拟后台返回数据 //在app.js 可以发现下面的代码
app.use('/', indexRouter);
app.use('/users', usersRouter);
- 配置相关路由
var indexRouter = require('./routes/index');//引入首页的路由模块
app.use('/index', indexRouter);//配置请求路径
- 接受用户请求 express有三种方式可以接受用户的请求
get('/地址',function(req,res){});
post(…)
use(…) //use 模式下get和post 通吃
//回调函数中可以接受三个参数,其中第三个参数为next函数,开启后还可以执行下一次请求
node.js连接mysql
- 安装驱动
cnpm install mysql
- 连接数据库
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'test'
});
connection.connect();
connection.query('SELECT * FROM studnet ',(err,data)=>{
console.log(data)//输出student表中的内容
}
});
- MySql常用指令
- select 某列 from table;
- select distinct 某列 from table; 列出不同(distinct)的值。
- select 列名称 from 表名称 where 列 运算符 值;条件查询(运算符:= <> >= between like)
- select * from table where name='asdf'and id=1;and运算符实例
- select * from table where (name='dasdf' or id=23) and a_id='23';or +and混合运算符
- select * from table order by 列名称; order by 排序
- insert into table values ('值','值' ,'值','值');插入新的行
- insert into table (列名称,列名称) values ('值','值');给指定列插入数据
- update table set 列名称=新值,列名称=新值 where id=2; Update修改表中的 数据。
- delete from table where id=1; 删除某行
- delete from table;删除所有行