5. Node.js express 请求拦截,统一处理参数,返回结果

1,585 阅读1分钟

拦截方法

  1. 在app.js 中新增如下代码, 拦截所有请求
app.all('/*', function (req, res, next) {

    // get, post 参数统一获取
    req.getParams = function () {
        return { ...req.query, ...req.body, ...req.params }
    };

    res.ok = function (data) {
        res.json({ code: 200, message: 'ok', data: data });
    }

    res.error = function (message, code = 0) {
        res.json({ code: code, message });
    }

    next();
})

image.png

  1. 在api中使用, 修改test方法
app.get('/test', (req, res, next) => {
    console.log(req.params);
    mysql.table('sys_captcha').select().then(data => {
        res.ok(data);
    })
})

3. 重启app.js

4. 在浏览器中打开 http://localhost:8082/test?aaa=111

image.png

控制台输出, 获取到了请求参数

image.png

可以在拦截器里统一加解密参数, 根据不同的前缀拦截

app.all('/api/*', ...); 拦截所有api开头的请求