NodeJS/Express 使用多个 req.query.params 构建URL

huangapple go评论84阅读模式
英文:

NodeJS/Express Build URL using multiple req.query.params

问题

我有一个小的Express API应用程序,它通过调用外部API来工作。我正在尝试基于传入我的API的查询参数构建外部API的URL。我尝试使用if/else块,但常量仅在该块内部可用。

这是我目前的代码:

const baseUrl = https://externalapi.com/api&apikey=<APIKEY>;
const response = await axios.get(url);

所以我想要能够根据传入的参数在baseUrl上添加查询参数,如果用户有一个名为param1的参数,那么将其添加到baseUrl以构建url,但如果他们指定了param2,那么也添加它,或者两者的组合。

英文:

I have a small express API app which makes calls to an external API. I am trying to build the URL for the external API based on query parameters incoming to my API. I have tried to use an if/else block but the const is only available within that block.

Here is what I have so far:

const baseUrl = https://externalapi.com/api&apikey=<APIKEY>;
const response = await axios.get(url);

So I want to be able to add query parameters onto the baseUrl based on what ones come in, so if a user has a param of param1 then add this to baseUrl to make url but if they specify param2 then add this as well or a combination of one or the other or both

答案1

得分: 1

如果在if或else子句中设置变量,它们需要是变量,而不是const。并且,它们需要在if / else子句之外声明。

let foo
if (a) foo = 'a'
else foo = 'b'

你的应用程序可能会使用node的URL类

const targetUrl = new URL('https://externalapi.com/api')
targetUrl.searchParams.append('apikey', '<<SECRET API KEY>>') //安全问题!

if (a) targetUrl.searchParams.append('objecttype', 'a')
else targetUrl.searchParams.append('objecttype', 'b')

你可以使用URL类的.searchParams属性来组装你的查询。

安全提示:你可能应该使用POST而不是GET来调用这个API,并将敏感参数(如你的秘密API密钥)放入POST参数中。URL上的参数会存储在Web服务器日志中。它们可能存储在不受你或外部API提供者控制的代理服务器日志中。解释如何重构你的代码以执行这些操作超出了本SO答案的范围。

英文:

If you set variables within if or else clauses, they need to be variables, not consts. And, they need to be declared outside the if / else clauses.

let foo
if (a) foo = &#39;a&#39;
else foo = &#39;b&#39;

A possibility for your application might use node's URL classes.

const targetUrl = new URL(&#39;https://externalapi.com/api&#39;)
targetUrl.searchParams.append(&#39;apikey&#39;, &#39;&lt;&lt;SECRET API KEY&gt;&gt;&#39;) //SECURITY PROBLEM!

if (a) targetUrl.searchParams.append(&#39;objecttype&#39;, &#39;a&#39;)
else targetUrl.searchParams.append(&#39;objecttype&#39;, &#39;b&#39;)

You can use the .searchParams property of the URL class to assemble your query.

Security tip: You probably should use POST rather than GET to call this API, and put your sensitive parameters (like your secret API key) into the POST parameters. Parameters on URLs are stored in web server logs. They may be stored in proxy server logs that aren't controlled by you or the provider of your external api. Explaining how to refactor your code to do that is beyond the scope of this SO answer.

huangapple
  • 本文由 发表于 2020年1月6日 20:48:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612414.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定