Node js将查询字符串传递给url

x6492ojm  于 2023-10-17  发布在  Node.js
关注(0)|答案(2)|浏览(104)

我正在使用request promise插件request来创建get和post API。我想用一个参数传递URL。下面是我的代码。如何在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;
    
}
wkyowqbh

wkyowqbh1#

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

nfzehxib2#

要通过URL传递参数,可以像这样传递:

http://localhost:3000/api/student/?id={student_id}&branch={studentbranch}

相关问题