Node.js: differenza tra req.query [] e req.params


124

C'è una differenza tra l'ottenimento di argomenti QUERY_STRING tramite req.query[myParam]e req.params.myParam? In caso affermativo, quando dovrei usare quale?

Risposte:


142

req.paramscontiene parametri di route (nella parte del percorso dell'URL) e req.querycontiene i parametri di query dell'URL (dopo ?il nell'URL).

Puoi anche usare req.param(name)per cercare un parametro in entrambi i posti (oltre che req.body), ma questo metodo è ora deprecato.


Ah, ok, grazie, quindi entrambi sono forniti da Express. E i dati POST a cui accedo tramite req.body.myParam?

1
Destra. Quale usare dipende da cosa stai cercando di fare.
JohnnyHK

Nota anche: "L'accesso diretto a req.body, req.params e req.query dovrebbe essere preferito per chiarezza, a meno che tu non accetti veramente l'input da ogni oggetto." - documentazione espressa
Ryan Q

2
req.paramè ora deprecato. Node suggerisce di usare req.queryoreq.params
SaiyanGirl

3
perché deprecarlo? cosa succede se usiamo params o query e poi decidiamo di cambiarlo in un altro?
John il

247

Dato questo percorso

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

e dato questo URL http://www.google.com/hi/there?qs1=you&qs2=tube

Tu avrai:

req. domanda

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

req. params

{
  param1: 'there'
}

Express req.params >>


E se avessi bisogno di ottenere / hi /?
daniel

2
dai un'occhiata a req.url o req.originalUrl o req._originalUrl, quindi dividi su/
ruffrey il

22

Supponiamo di aver definito il nome del percorso in questo modo:

https://localhost:3000/user/:userid

che diventerà:

https://localhost:3000/user/5896544

Qui, se stamperai: request.params

{
userId : 5896544
}

così

request.params.userId = 5896544

quindi request.params è un oggetto contenente proprietà per la rotta denominata

e request.query proviene dai parametri di query nell'URL, ad esempio:

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

request.query

{

userId: 5896544

}

così

request.query.userId = 5896544

Buona spiegazione
Abk

7

Ora dovresti essere in grado di accedere alla query utilizzando la notazione punto.

Se vuoi accedere, dì che stai ricevendo una richiesta GET a /checkEmail?type=email&utm_source=xxxx&email=xxxxx&utm_campaign=XXe vuoi recuperare la query utilizzata.

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

I parametri vengono utilizzati per il parametro auto-definito per la ricezione della richiesta, qualcosa come (esempio):

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)});
});

0

Voglio menzionare una nota importante in merito req.query, perché attualmente sto lavorando sulla funzionalità di impaginazione basata su req.querye ho un esempio interessante da dimostrarti ...

Esempio:

// 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
    });
  });
};

Noterai il +segno davanti a req.query.pageSizeereq.query.currentPage

Perché? Se elimini +in questo caso, riceverai un errore e tale errore verrà generato perché utilizzeremo un tipo non valido (con messaggio di errore il campo "limite" deve essere numerico).

Importante : per impostazione predefinita, se estrai qualcosa da questi parametri di query, sarà sempre una stringa , perché arriva l'URL ed è trattato come un testo.

Se abbiamo bisogno di lavorare con i numeri e convertire le istruzioni della query da testo a numero, possiamo semplicemente aggiungere un segno più davanti all'istruzione.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.