req.query
説明
Google翻訳してみると、
解析されたクエリ文字列を含む辞書
「辞書!?」
まあ、「dictionary」とか書いてますもんね。
英語弱いし、そんなにIT用語に詳しいわけではないので、スルーします。
ただ、こいつはよく使っております。
書いてある通り、「クエリ文字列」を取得するものです。
クエリ文字列は、URLパラメーターのことですね。
http://{ }/search?id=xxx&attr=oooo
これ。太字のところです。
使い方
"http://{ --^^--==~ }/info?id=0001&name=rascal&attr=Mammalia" をURLとしてリクエストとするとします。
root@RascalRoom:~# curl http://{ --^^--==~ }/info?id=0001&name=rascal&attr=Mammalia
コントローラーを、
/** * RoomController * * @description :: Server-side actions for handling incoming requests. * @help :: See https://sailsjs.com/docs/concepts/actions */ module.exports = { /** * `RoomController.info()` */ info: async function (req, res) { console.log(req.query.id); console.log(req.query.name); console.log(req.query.attr); return res.ok(); } };
すると、
info: Starting app... info: ・? Auto-migrating... (alter) info: Hold tight, this could take a moment. info: ? Auto-migration complete. info: info: .-..-. info: info: Sails <| .-..-. info: v1.2.3 |\ info: /|.\ info: / || \ info: ,' |' \ info: .-'.-==|/_--' info: `--'-------' info: __---___--___---___--___---___--___ info: ____---___--___---___--___---___--___-__ info: info: Server lifted in `/app/app1` info: To shut down Sails, press+ C at any time. info: Read more at https://sailsjs.com/support. debug: ------------------------------------------------------- debug: :: Sat Jul 06 2019 16:39:07 GMT+0000 (Coordinated Universal Time) debug: Environment : development debug: Port : 1337 debug: ------------------------------------------------------- 0001 rascal Mammalia
こうなります。
req.query にはクエリ文字列が格納されていますね。
オブジェクトとして格納されるので、
req.query.{パラメータ名} で、値が出てきます。
まとめ
req.query はクエリ文字列を受け取るもの。
クエリ文字列は、URLパラメーターのこと。
つまり、GETメソッドを使用した場合に使います。
POST の場合は、リクエストボディにデータが格納されます。
req.body です。