英文:
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 const
s. And, they need to be declared outside the if / else clauses.
let foo
if (a) foo = 'a'
else foo = 'b'
A possibility for your application might use node's URL classes.
const targetUrl = new URL('https://externalapi.com/api')
targetUrl.searchParams.append('apikey', '<<SECRET API KEY>>') //SECURITY PROBLEM!
if (a) targetUrl.searchParams.append('objecttype', 'a')
else targetUrl.searchParams.append('objecttype', 'b')
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论