express框架
express是基于 Node.js 平台,快速、开放、极简的 Web 开发框架
手动创建工程
$mkdir 文件名 创建工程文件夹
$cd 文件名 定位到工程文件夹
$npm init -y 初始化项目(package.json)
$npm i -S express 安装express
目录结构:
node_modules
▽public
user.html
▽routers
user.js
index.js
package-lock.json
package.json
index.js 为入口文件
整个项目为一个服务,提供多种服务:1.接口 2.静态资源(页面)
后面引入的一些插件,大多都是函数
核心代码
index.js
const express =require('express')
const app=express() //app为Express的实例对象
app.get('/findAll',(req,resp)=>{
// var sql="select username as name,age from users order by id"
var stus=[{name:'zhangsan',age:10},{name:'xiaoming',age:11}] //模拟了一个查询后的数据
resp.send({ //输出结果
status:200,
message:'success',
data:stus,
time:new Date().getTime()
})
}); //接口
app.listen('3000',()=>{
console.log('http://localhost:3000');
}) // 3000 为端口号 在浏览器地址栏中输入http://localhost:3000,即可访问该服务器
路由定义
定义了针对客户端请求的处理函数,不同url对应不同的处理函数
。
通过Express的实例对象app上的请求方法定义不同的路由,例如:get、post、delete、put、all…
创建router文件夹,作为路由文件夹,可以创建不同的文件设置不同模块的路由。
例 创建 router/users.js 创建user模块的路由,放置user模块相关的接口。
router/users.js
const express =require('express')
const router =express.Router(); //创建一个路由模块
路由接口
module.exports=router; //导出该模块
index.js
var usersRouter = require('./routes/users'); //从users模块引入
app.use('/users', usersRouter); //第一个参数/users会与路由接口中的路径进行拼接
路由参数
带有参数的路径的不同表现形式
1.
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
2.
Route path: /users
Request URL: http://localhost:3000/users?id=1&name=terry
req.query: { "id": "1", "name": "terry" }
response方法
Method | Description |
---|---|
res.download() | Prompt a file to be downloaded. |
res.end() | End the response process. |
res.json() | Send a JSON response. |
res.jsonp() | Send a JSON response with JSONP support. |
res.redirect() | Redirect a request. |
res.render() | Render a view template. |
res.send() | Send a response of various types. |
res.sendFile() | Send a file as an octet stream. |
res.sendStatus() | Set the response status code and send its string representation as the response body. |
中间件
一些插件,安装后可以使用,基本上都是函数
-
body-parser
app.post()/router.post()方法中,获取数据体部(req.body)时,需要中间件body-parser安装:npm i -S body-parser
index.jslet bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({extended:false})); //转换查询字符串(表单) app.use(bodyParser.json()); //转换为json格式
-
serve-static
访问静态资源
安装:npm i -S serve-static
index.jslet serveStatic=require("serve-static"); app.use(serveStatic("public")) //注册静态资源中间件 参数为静态资源文件夹名 (会从该文件夹中查找静态资源,例html文件)
在public文件夹中创建user.html文件(静态资源),在浏览器中通过
localhost:3000/user.html
可以直接访问到该页面。 -
cors
解决跨域问题
安装:npm i -S cors
index.jslet cors=require('cors'); app.use(cors({ "origin": "*", ////白名单(可以进行跨域访问) * 表示所有地址都可以跨域访问 "methods": "GET,HEAD,PUT,PATCH,POST,DELETE", "preflightContinue": false, "optionsSuccessStatus": 204 })); //注册cors
注意注册cors的代码需要写在
路由注册代码之前
才能生效 -
cookie-parser
安装: npm i cookie-parser
index.jslet cookieParser=require('cookie-parser') //引入cookie app.use(cookieParser()) //注册cookie //设置cookie app.get('/setcookie',(req,resp)=>{ //原生语法 // resp.writeHead(200,{ // "Set-Cookie":"name=zhangsan" // }) // resp.end() resp.cookie('name','zhangsan'); resp.end('设置成功') }) //getcookie app.get('/getcookie',(req,resp)=>{ //原生语法 // console.log(req.headers); console.log(req.cookies); })
通过
localhost:3000/setcookie
和localhost:3000/getcookie
进行访问
以下展示框架实例:
index.js
//整个项目为一个服务,提供多种服务
//1.接口 2.静态资源(页面)
//后面引入的一些插件,大多都是函数
const express =