[node.js] Node.js : req.query []와 req.params의 차이점

req.query[myParam]및을 통해 QUERY_STRING 인수를 얻는 데 차이가 req.params.myParam있습니까? 그렇다면 언제 사용해야합니까?



답변

req.params경로 매개 변수 (URL의 경로 부분에 있음)를 req.query포함하고 URL 쿼리 매개 변수 ( ?URL에서 뒤에 있음 )를 포함합니다.

를 사용 req.param(name)하여 두 위치 (및)에서 매개 변수를 조회 할 수도 req.body있지만이 메서드는 이제 더 이상 사용되지 않습니다.


답변

이 경로가 주어지면

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

이 URL이 주어졌습니다.
http://www.google.com/hi/there?qs1=you&qs2=tube

당신은 할 것:

req. 질문

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

req. 매개 변수

{
  param1: 'there'
}

Express req.params >>


답변

다음과 같이 경로 이름을 정의했다고 가정합니다.

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


답변

이제 점 표기법을 사용하여 쿼리에 액세스 할 수 있습니다.

액세스하려는 경우에서 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)});
});


답변

에 관한 한 가지 중요한 참고 사항을 언급하고 싶습니다. req.query현재 저는 페이지 매김 기능을 기반으로 작업하고 있으며 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

왜? +이 경우 삭제 하면 오류가 발생하고 잘못된 유형을 사용하므로 해당 오류가 발생합니다 (오류 메시지 ‘제한’필드는 숫자 여야 함).

중요 : 기본적으로 이러한 쿼리 매개 변수에서 무언가를 추출 하는 경우 URL이오고 텍스트로 처리되므로 항상 문자열 이됩니다.

숫자로 작업하고 쿼리 문을 텍스트에서 숫자로 변환해야하는 경우 문 앞에 더하기 기호를 추가하기 만하면됩니다.


답변