素敵なテクニックエクスプレスのリクエストオブジェクトのクエリ、パラメータ、ボディフィールドをマージするオブジェクトを作成することです。
//./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);
});
これはそれがいいとばかりに「掘り下げる」ために便利になりユーザーが要求に応じて送信した可能性があるすべての「カスタムデータ」。
注
なぜ '小道具' フィールド?これはカットダウンスニペットであるため、私はこのAPIをいくつかの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";
}
}
あなたはどのように "ID" を検証する方法を教えていただけますか? –
@AnandRaj:どういう意味ですか? "id"を検証する方法は?どのようなバリデーションが必要ですか?ところで、あなたの関数では、 'id sample'の値を' var sampleId = req.params.id; 'のように得ることができます。 –
最新版では 'req.params.whatever'を使用してください。 – adelriosantiago