express

express安装:npm install express -D(--save dev)

const express = require('express'),
      app = express();//使用express 已经创建服务
app.get('/favicon.ico',(req,res)=>{
    req.send();
});
app.get('/',(req,res)=>{
    //req:客户端请求时携带的信息
    //res:服务器端响应时携带的信息
    res.setHeader('Content-Type','text/plain;utf-8');
    res.end('helloworld');
    // res.send('hello world');//自动根据内容设置mime类型,并调用res.end断开客户端与服务器端的连接
});
app.listen(8080,function () {
    console.log('8080端口被启用');
});

req.params  //路由传参部分

req.query  //问号传参部分

req.path //请求的路径pathname

参数有路由传参和问号传参

拿到路由传参

/*express上给req和res提供的方法*/
const express = require('express'),
      app = express();
app.listen(8080,function () {
    console.log('8080');
});
app.get('/user/:id/:name',function (req,res) {//:后面表示客户端传的参数
    //req.params 拿到所有的参数对象
    console.log(req.path);//  /user/2/lily
    console.log(req.params.name);//vue react 用的多    req.params.id路由参数(http://localhost:8080/user/2/lily)
})

拿到问号传参

app.get('/user',function (req,res) {
    console.log(req.query);//拿到问号传参部分  http://localhost:8080/user?id=2
    console.log(req.query.id);

console.log(req.path); // /user
res.send(); })

res.json({name:lily})  转换成json格式数据

res.send( )  包含了res.json方法的功能

res.set( )  设置响应头

res.sendStatus(200) 设置响应状态码

res.redirect(‘/另一个接口’)    接口之间的跳转

res.sendFile(path,[..options],fn);   跳静态页面 需要拿到该页面并再客户端渲染出来

res.render()   渲染模板  ejs模板  <%=%>   <%if(){%>

中间件

路由中间件 应用中间件 错误处理的中间件 内置中间件 第三方中间件(cookie-parser body-parser)

/*中间件*/
const express = require('express'),
      app = express();
app.use(function (req,res,next) {//处理公共逻辑  不管请求方式是什么 进来先走app.use中间件
    console.log('Time', new Date().toLocaleString());
    next();//才会往下运行
});
app.use('/user',function (req,res,next) {//这个中间件表示   只要这个接口匹配就运行此中间件
    console.log('Reauest Type', req.method);
    next();
});
app.get('/user',function (req,res,next) {
    res.send('USER');
});
app.listen(8080);
原文地址:https://www.cnblogs.com/Lia-633/p/9897383.html