我已经开始在 express 上的一些应用程序中使用的一个很好的技术是创建一个对象,该对象合并 express 请求对象的查询、参数和正文字段。
//./express-data.js
const _ = require("lodash");
class ExpressData {
/*
* @param {Object} req - express request object
*/
constructor (req) {
//Merge all data passed by the client in the request
this.props = _.merge(req.body, req.params, req.query);
}
}
module.exports = ExpressData;
然后在您的控制器主体中,或在快速请求链范围内的任何其他地方,您可以使用如下内容:
//./some-controller.js
const ExpressData = require("./express-data.js");
const router = require("express").Router();
router.get("/:some_id", (req, res) => {
let props = new ExpressData(req).props;
//Given the request "/592363122?foo=bar&hello=world"
//the below would log out
// {
// some_id: 592363122,
// foo: 'bar',
// hello: 'world'
// }
console.log(props);
return res.json(props);
});
这使得“深入研究”用户可能随请求发送的所有“自定义数据”变得既方便又方便。
注意
为什么是“道具”字段?因为那是一个精简的 sn-p,所以我在我的许多 API 中都使用了这种技术,我还将身份验证/授权数据存储到这个对象上,示例如下。
/*
* @param {Object} req - Request response object
*/
class ExpressData {
/*
* @param {Object} req - express request object
*/
constructor (req) {
//Merge all data passed by the client in the request
this.props = _.merge(req.body, req.params, req.query);
//Store reference to the user
this.user = req.user || null;
//API connected devices (Mobile app..) will send x-client header with requests, web context is implied.
//This is used to determine how the user is connecting to the API
this.client = (req.headers) ? (req.headers["x-client"] || (req.client || "web")) : "web";
}
}