这个API连接请求字符串缺少什么?
我的api_密钥位于“.env”中。我可能想得太多了。这是我目前的代码,在不隐藏api_密钥的情况下工作。从process.env.API_键提取时,语法不正确这个API连接请求字符串缺少什么?,api,ticker,Api,Ticker,我的api_密钥位于“.env”中。我可能想得太多了。这是我目前的代码,在不隐藏api_密钥的情况下工作。从process.env.API_键提取时,语法不正确 function call_api(finishedAPI, ticker) { request('https://cloud.iexapis.com/stable/stock/' + ticker + '/quote?token= + 'api_key', { json: true }, (err, res, body) =&
function call_api(finishedAPI, ticker) {
request('https://cloud.iexapis.com/stable/stock/' + ticker + '/quote?token= + 'api_key', { json: true }, (err, res, body) => {
if (err) {return console.log(err);}
if (res.statusCode === 200){
finishedAPI(body);
};
});
};
我知道有一种更简单的方法可以做到这一点,而且我对谷歌线索的研究并不是全力以赴。我会在星巴克给你买咖啡或番茄罗勒帕尼尼:-)应该是。看起来您还试图错误地使用回调 注意不过,很容易判断您应该始终声明所使用的语言。只是让每个人都容易
function call_api(ticker, finishedAPI) {
request({url: 'https://cloud.iexapis.com/stable/stock/' + ticker + '/quote?token= + 'api_key'}, { json: true }, (err, res, body) => {
if (err) {return console.log(err);}
if (res.statusCode === 200){
finishedAPI(body);
};
});
};
function main(){
call_api(ticker, function(fromCallapi){
if(fromCallapi) console.log(fromCallapi);
})
}
回调将在另一个方法或操作中调用,并在操作完成后返回给调用者,通过将进程、变量或方法传递回调用者
注意应将参数finishedAPI
重命名为callback
最佳做法是指示进程、变量或方法将结果返回给调用者。请注意,过度使用回调可能会全面影响应用程序的性能,并可能挂起进程。希望有帮助
更新
如果您计划使用.env
您需要使用require('dotenv').config(路径:'/path/to/.env')
一旦加载,例如访问名为VARIBLE\u NAME
的变量,您将使用process.env.VARIBLE\u NAME
函数调用api(finishedAPI,ticker)访问env变量{
请求('https://cloud.iexapis.com/stable/stock/“+ticker+”/quote?token='+API_KEY,{json:true},(err,res,body)=>{
if(err){return console.log(err);}
如果(res.statusCode==200){
finishedAPI(主体);
};
});
}; 谢谢你的回复。我了解回调函数是如何工作的。我无法从将api_键一次包含在.env中的最佳方式中“解脱”