Express - 使用请求对象

中间件以及路由函数接收的第一个参数就是request对象

1. request对象常用属性

  • method 请求方法
  • path 请求路径 (GET参数不包含在path中)
  • url 请求url (除域名外的完整URL,包含GET参数)
  • query GET参数对象
  • params 路由参数对象
  • headers 请求报头
  • cookies 请求cookie (需要使用cookie-parase中间件)
  • ip 客户端ip
  • body POST请求数据 (需要使用body-parser中间)
app.get('/user/:userId', (req, resp) => {
  resp.json({
    method: req.method,
    path: req.path,
    url: req.url,
    query: req.query,
    params: req.params,
    headers: req.headers,
    cookies: req.cookies,
    ip: req.ip
  });
});

// http://localhost:8080/user/1?name=leon&test=1"
{
  "method": "GET",
  "path": "/user/1",
  "url": "/user/1?name=leon&test=1",
  "query": {
     "name": "leon",
     "test": "1"
  },
  "params": {
    "userId": 1
  },
  "headers": {
    "host": "localhost:8080",
    "connection": "keep-alive",
    ....
  },
  cookies: "Httew=121223",
  ip: "::1"
}

2. 请求对象中的cookie处理

  • 安装cookie-parser 中间件
    npm install cookie-parser --save
  • 使用cookie-parser中间件处理cookie
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();

app.use(cookieParser());
app.get('/', (req, resp) => {
  resp.json({cookies: req.cookies });
});

app.listen(8080, () => {
  console.log('listen on 8080');
});

3. 请求对象的body体处理

  • 安装body-parser中间件
    npm install body-parser --save
  • 使用body-parser中间件处理body体
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser());
app.post('/', (req, resp) => {
  resp.json(req.body);
});

app.listen(8080, () => {
  console.log('listen on 8080');
});
posted @ 2022-02-20 19:40  箫笛  阅读(117)  评论(0)    收藏  举报