169

とを介してQUERY_STRING引数を取得することには違いがreq.query[myParam]ありreq.params.myParamますか?もしそうなら、私はいつどちらを使うべきですか?

4

6 に答える 6

329

このルートを考えると

app.get('/hi/:param1', function(req,res){} );

そしてこのURLを与えられた http://www.google.com/hi/there?qs1=you&qs2=tube

あなたが持っているでしょう:

必須 クエリ

{
  qs1: 'you',
  qs2: 'tube'
}

必須 パラメータ

{
  param1: 'there'
}

Express req.params >>

于 2013-01-24T18:27:20.560 に答える
187

req.paramsルートパラメータ(URLのパス部分)をreq.query含み、URLクエリパラメータ(URLの後に)を含み?ます。

req.param(name)を使用して両方の場所(および)でパラメータを検索することもできますreq.bodyが、このメソッドは非推奨になりました。

于 2013-01-19T19:37:21.820 に答える
51

次のようにルート名を定義したとします。

https://localhost:3000/user/:userId

これは次のようになります:

https://localhost:3000/user/5896544

ここで、印刷する場合: request.params

{
userId : 5896544
}

それで

request.params.userId = 5896544

したがって、request.paramsは、指定されたルートへのプロパティを含むオブジェクトです。

request.queryは、URLのクエリパラメータから取得されます。例:

https://localhost:3000/user?userId=5896544 

request.query

{

userId: 5896544

}

それで

request.query.userId = 5896544

于 2019-05-17T10:06:12.353 に答える
8

これで、ドット表記を使用してクエリにアクセスできるようになります。

アクセスしたい場合は、でGETリクエストを受信して​​いて、使用したクエリ/checkEmail?type=email&utm_source=xxxx&email=xxxxx&utm_campaign=XXを取得したいとします。

var type = req.query.type,
    email = req.query.email,
    utm = {
     source: req.query.utm_source,
     campaign: req.query.utm_campaign
    };

パラメータは、リクエストを受信するための自己定義パラメータに使用されます(例):

router.get('/:userID/food/edit/:foodID', function(req, res){
 //sample GET request at '/xavg234/food/edit/jb3552'

 var userToFind = req.params.userID;//gets xavg234
 var foodToSearch = req.params.foodID;//gets jb3552
 User.findOne({'userid':userToFind}) //dummy code
     .then(function(user){...})
     .catch(function(err){console.log(err)});
});
于 2017-08-24T14:48:52.527 に答える
1

req.query現在、に基づいてページ付け機能に取り組んでおり、あなたに示すための興味深い例が1つあるため、に関する重要な注意事項を1つ挙げておきreq.queryます。

例:

// Fetching patients from the database
exports.getPatients = (req, res, next) => {

const pageSize = +req.query.pageSize;
const currentPage = +req.query.currentPage;

const patientQuery = Patient.find();
let fetchedPatients;

// If pageSize and currentPage are not undefined (if they are both set and contain valid values)
if(pageSize && currentPage) {
    /**
     * Construct two different queries 
     * - Fetch all patients 
     * - Adjusted one to only fetch a selected slice of patients for a given page
     */
    patientQuery
        /**
         * This means I will not retrieve all patients I find, but I will skip the first "n" patients
         * For example, if I am on page 2, then I want to skip all patients that were displayed on page 1,
         * 
         * Another example: if I am displaying 7 patients per page , I want to skip 7 items because I am on page 2,
         * so I want to skip (7 * (2 - 1)) => 7 items
         */
        .skip(pageSize * (currentPage - 1))

        /**
         * Narrow dont the amound documents I retreive for the current page
         * Limits the amount of returned documents
         * 
         * For example: If I got 7 items per page, then I want to limit the query to only
         * return 7 items. 
         */
        .limit(pageSize);
}
patientQuery.then(documents => {
    res.status(200).json({
        message: 'Patients fetched successfully',
        patients: documents
    });
  });
};

との前に+サインがreq.query.pageSizeありますreq.query.currentPage

なんで?この場合に削除する+と、エラーが発生し、無効なタイプを使用するため、そのエラーがスローされます(エラーメッセージの「limit」フィールドは数値である必要があります)。

重要:デフォルトでは、これらのクエリパラメータから何かを抽出する場合、URLが送信され、テキストとして扱われるため、常に文字列になります。

数値を操作し、クエリステートメントをテキストから数値に変換する必要がある場合は、ステートメントの前にプラス記号を追加するだけです。

于 2019-04-08T19:42:20.503 に答える
0

axios(GET / POST)から来ている場合は、構成を介してquery/url params(で読み取り可能)を使用可能にすることを追加したいと思います。req.query

axios.post('/users', {...data}, {
  headers: {...anyHeaders},
  params: {uid: `${uid}`}
})

そして、パスを介してpath/route variables(で読み取り可能)を利用可能にします。req.params

axios.get(`/users/${uid`}, {
  headers: {...anyHeaders}
})

これも追加します。サーバーでクエリパラメーターを読み取るために使用される名前は、クライアントからの名前と一致する必要があります。これは、パス/ルートの一部が使用可能であるという条件で、サーバー上で任意の名前を使用できるパス変数には当てはまりません(基本的には置換を行います-ちょっとそれがどのようreact-routerに行われるかのように:) /path/:variable

于 2021-07-18T09:21:36.597 に答える