当前位置:网站首页>express框架详解
express框架详解
2022-07-06 09:14:00 【进阶日记】
Express
使用express可以快速创建web网站服务器或者API接口服务器
1.创建express的web服务器
// 导入express
const express = require("express")
// 创建web服务器
const app = express()
// 启动web服务器
app.listen(8088,()=>{
console.log('http://127.0.0.1:8088');
})
2. 监听get/post请求
// 监听GET请求并返回响应内容,第一个参数为请求的url
app.get('/get',(req,res)=>{
//req.query获取请求是发送的参数
console.log(req.query)//http://127.0.0.1:8088/get?name=zs&age=18
//{ name: 'zs', age: '18' }
// 调用express提供的res.send()方法,设置返回的JSON对象
res.send({name:"zs",age:20,gender:"男"})
})
// 监听POST请求并返回响应内容,第一个参数为请求的url
app.post('/post',(req,res)=>{
// 调用express提供的res.send()方法,设置返回的JSON对象
res.send({name:"zs",age:20,gender:"男"})
})
向http://127.0.0.1:8088/post发送请求返回值为
{ "name": "zs",
"age": 20,
"gender": "男"}
3.获取参数
//静态参数
app.get('/get',(req,res)=>{
//req.query获取请求是发送的参数
//http://127.0.0.1:8088/get?name=zs&age=18
res.send(req.query)
//{ name: 'zs', age: '18' }
})
//动态参数
app.get('/getId/:id',(req,res)=>{
//req.query获取请求是发送的参数
//http://127.0.0.1:8088/getId/12
res.send(req.params)
})
//返回
{
"id": "12"
}
//多个动态参数
app.get('/getId/:id/:name',(req,res)=>{
//req.query获取请求是发送的参数
//http://127.0.0.1:8088/getId/12/zs
res.send(req.params)
})
//返回
{
"id": "12"
"name":"zs"
}
4. 中间件
//app.use()作用为注册全局中间件,app.use('path',function())第一个参数为路径若为/可省略
express中间件分成三种
1.内置中间件 static
2.自定义中间件
3.第三方中间件 (body-parser) (拦截器)
app.use(express.static('public'))
app.use(express.static('dome'))
//可以直接访问到
http://127.0.0.1:8088/index.html
http://127.0.0.1:8088/index.css
http://127.0.0.1:8088/index.js
//会优先查找public文件中的index文件,如果找不到就找dome中的index文件
app.use('/public',express.static('public'))
//访问时要http://127.0.0.1:8088/public/index.html
//自定义全局生效的中间件 可以定义多个中间件,会按顺序调用中间件
app.use(function (req, res, next) {/*表示匹配任何路由*/
console.log(new Date())
next()/*表示匹配完成这个中间件就继续往下执行。*/
})
//局部中间件
let func = function (req, res, next) {/*表示匹配任何路由*/
console.log(new Date())
next()/*表示匹配完成这个中间件就继续往下执行。*/
}
//可以定义多个局部中间件
app.get('/',func1,func2,(req,res)=>{
res.send('get router为:/')
})
//使用中间件来处理请求数据
app.use(express.json())
app.use(express.urlencoded({extended:false})
//使用第三方中间件 (body-parser) (拦截器)
1. npm install body-parser
//到如中间件
const parser = require("body-parser")
//注册中间件
app.use(parser.urlencoded({extended:false})
//nodejs内置querystring模块处理查询字符串将查询字符串转为对象格式
const qs = require("querystring")
console.log(qs.parse(str))
5. nodemon
能够不用频繁启动修改后的项目,nodemon会自动重启项目方便开发和测试
npm install -g nodemon
使用nodemon app.js来运行项目,不用node app.js
6. 路由
1. 原始方式挂载
const express = require("express")
const app = express();
// 挂载路由
app.get('/',(req,res)=>{
res.send('get router为:/')
})
app.post('/',(req,res)=>{
res.send('post router为:/')
})
app.listen(8088,()=>{
console.log("http://127.0.0.1:8088");
})
2.使用express路由
//在router.js中创建路由对象
const express = require("express")
const router = express.Router();
// 挂载具体路由
router.get('/user/list',(rep,res)=>{
res.send("GER user list")
})
router.post("/user/add",(req,res)=>{
res.send("POST user add")
})
// 向外导出路由对象
module.exports = router
//在index.js中引用路由
const express = require("express")
const app = express()
// 导入路由模块
const router = require("./router")
// 注册路由模块
app.use(router)
app.listen(8088,()=>{
console.log("http://127.0.0.1:8088");
})
//app.use('/api',router)//为路由添加统一前缀http://127.0.0.1:8088/api/user/add
7.编写get/post接口
const express = require("express");
const app = express()
const router = express.Router()
app.use(express.urlencoded({extended:false}))
router.get('/get',(req,res)=>{
// 客户端发送的请求数据
const query = req.query;
res.send({
status:0,//0表示成功,1表示失败
msg:"GET请求成功",//状态的描述
data:query//需要响应给客户端的数据
})
})
router.post('/post',(req,res)=>{
// 客户端发送的请求数据
const body = req.body;
// 配置解析表单数据的中间价
res.send({
status:0,//0表示成功,1表示失败
msg:"POST请求成功",//状态的描述
data:body//需要响应给客户端的数据
})
})
app.use(router);
app.listen(8088,()=>{
console.log("get请求");
})
8.cors跨域解决
const express = require("express");
const cors = require("cors")
const app = express()
//使用第三方中间件解决跨域
app.use(cors())
//自定义cors设置支持跨域的请求
var cors = function(req,res,next()){
res.header('Access-Control-Allow-Origin', 'http://localhost:8088');//请求地址
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');//请求方式
res.header('Access-Control-Allow-Headers', 'Content-Type');//请求头
next()
}
app.use(cors)
边栏推荐
猜你喜欢
Learn winpwn (3) -- sEH from scratch
Software I2C based on Hal Library
Introduction and use of automatic machine learning framework (flaml, H2O)
vs2019 使用向导生成一个MFC应用程序
安装numpy问题总结
打开浏览器的同时会在主页外同时打开芒果TV,抖音等网站
Use dapr to shorten software development cycle and improve production efficiency
Install mongdb tutorial and redis tutorial under Windows
Did you forget to register or load this tag
Machine learning notes week02 convolutional neural network
随机推荐
Classes in C #
AcWing 179.阶乘分解 题解
[蓝桥杯2020初赛] 平面切分
Unable to call numpy in pycharm, with an error modulenotfounderror: no module named 'numpy‘
L2-001 emergency rescue (25 points)
TCP/IP协议(UDP)
wangeditor富文本引用、表格使用问题
牛客Novice月赛40
[free setup] asp Net online course selection system design and Implementation (source code +lunwen)
How to set up voice recognition on the computer with shortcut keys
neo4j安装教程
QT creator uses Valgrind code analysis tool
Number game
Codeforces Round #753 (Div. 3)
Some notes of MySQL
库函数--(持续更新)
L2-006 树的遍历 (25 分)
[Blue Bridge Cup 2017 preliminary] grid division
Windows下安装MongDB教程、Redis教程
【kerberos】深入理解kerberos票据生命周期