node.jsrequestnpm-request

Node js passing query string to url


I am using the request promise plugin request to create the get and post api. I want to pass the URL with a parameter. below is my code. How to pass parameter value in URL?

async function getDetails (req) {

    var options = {
        url: 'http://localhost:3000/api/student/id/{studen_id}/branch/{studentbranch}',
        method: 'GET',
        headers: {
          'User-Agent': 'my request',
          'Authorization': 'Bearer {my token}',
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        json: true
      };

   let res= await rp(options)
    .then(function (body) {
        return body;
    })
    .catch(function (err) {
        console.log("error get balance",err)
    });

    return res;
    
}

Solution

  • async function getDetails (req) {
    
        var options = {
            url: 'http://localhost:3000/api/student/id/'+encodeURIComponent(req.body.id)+'/branch/'+encodeURIComponent(req.body.branch),
            method: 'GET',
            headers: {
              'User-Agent': 'my request',
              'Authorization': 'Bearer {my token}',
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            },
            json: true
          };
    
       let res= await rp(options)
        .then(function (body) {
            return body;
        })
        .catch(function (err) {
            console.log("error get balance",err)
        });
    
        return res;
        
    }