Một kỹ thuật tốt đẹp tôi đã bắt đầu sử dụng với một số ứng dụng của tôi trên express là tạo một đối tượng kết hợp các truy vấn, các tham số và các trường nội dung của đối tượng yêu cầu của 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;
Sau đó, trong cơ thể điều khiển của bạn, hoặc bất cứ nơi nào khác trong phạm vi của chuỗi yêu cầu rõ ràng, bạn có thể sử dụng một cái gì đó như dưới đây:
//./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);
});
này làm cho nó đẹp và tiện dụng để chỉ "đi sâu" vào tất cả "dữ liệu tùy chỉnh" mà người dùng có thể đã gửi cùng với yêu cầu của họ.
Note
Tại sao trường 'đạo cụ'? Vì đó là đoạn trích cắt giảm, tôi sử dụng kỹ thuật này trong một số API của mình, tôi cũng lưu trữ dữ liệu xác thực/ủy quyền vào đối tượng này, ví dụ bên dưới.
/*
* @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";
}
}
Nguồn
2017-10-09 08:51:29
Bạn có thể cho tôi biết cách xác thực "id" không? –
@AnandRaj: ý của bạn là gì: cách xác thực "id"? Bạn muốn loại xác thực nào?BTW, bạn có thể nhận giá trị 'id' trong hàm của bạn như sau:' var sampleId = req.params.id; '. –
Sử dụng 'req.params.whatever' trong các phiên bản mới nhất. – adelriosantiago