首页 > 解决方案 > 节点js将查询字符串传递给url

问题描述

我正在使用请求承诺插件请求来创建获取和发布 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;
    
}

标签: node.jsrequestnpm-request

解决方案


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

推荐阅读