如何在响应 Angular 客户端应用时发送 API 密钥
How do I send an API key in a response to an Angular client app?
我正在尝试使用 $http将我的 api 密钥从 NodeJS 路由到 Angular 客户端应用程序,但我不确定该怎么做。这是我的 NodeJS 文件:
//http://api.openweathermap.org/data/2.5/weather
var express = require('express');
var router = express.Router();
var request = require('request');
//GET http://localhost:3000
router.get('/', function(req, res, next) {
var env = process.env.WEATHER_API_KEY;
request({
url:'http://api.openweathermap.org/data/2.5/weather',
qs:req.query
},function(err,response,body){
if(err) return res.send(500,err);
res.send(body);
});
});
module.exports = router;
这是我的 Angular 文件:
NewsApp.directive('weather', function() {
return {
restrict: 'E',
scope: {
location: '=?'
},
controller: ['$scope', '$http', function($scope,$http){
$scope.location = 'Seattle,WA';
console.log($scope.location);
$http({
url:'/api/weather',
params:{
q:$scope.location,
APPID: //place API KEY here,
units:'imperial'
}
}).success(function(data){
console.log(data)
var weatherData = data.weather[0];
$scope.temperature = Math.round(data.main.temp);
$scope.city = data.name;
$scope.image = 'http://openweathermap.org/img/w/' + weatherData.icon + '.png';
})
}],
template:'<li class="weather"> '
Today''s temperature is: {{temperature}}°<img src="{{image}}">'
</li>',
replace: true,
transclude: true
}
});
当我在 APPID 之后的 params 对象中在我的角度文件中手动执行此操作时,我的应用程序工作正常,但我不希望我的 api 密钥可见,所以我想使用我的 .env 文件使用我的 nodejs 文件中的变量 env 通过后端传递它。
看起来
您希望在将查询字符串转发到 API 服务器之前对其进行修改。 因此,不要在客户端的查询字符串参数中包含 APPID,而是尝试在转发请求之前添加它。
...
//GET http://localhost:3000
router.get('/', function(req, res, next) {
req.query.APPID = process.env.WEATHER_API_KEY;
request({
url:'http://api.openweathermap.org/data/2.5/weather',
qs:req.query
},
...
您可以将密钥附加到服务器上的响应:
//GET http://localhost:3000
router.get('/', function(req, res, next) {
var env = process.env.WEATHER_API_KEY;
request({
url:'http://api.openweathermap.org/data/2.5/weather',
qs:req.query
},function(err,response,body){
if(err) return res.send(500,err);
res.send({app_key: env, data: body});
});
});
在 Angular 客户端应用中,您可以对密钥发出"GET"请求。收到后,您可以向天气 API 发出后续请求:
$http({
method: 'GET',
url: 'http://localhost:3000'
}).success(function(data) {
var app_key = data['app_key'];
// make the request to the API
http({
url:'/api/weather',
params: {
q: $scope.location,
APPID: app_key,
units:'imperial'
}
})
})
相关文章:
- API密钥使用和检查示例
- 基于api密钥的NodeJS web服务
- 带有新API密钥的Google Places Library OVER_QUERY_LMIT
- 如何在Ionic/Codova应用程序中保护我的Google Maps Javascript V3 API密钥
- 关于Parse.com客户端共享应用程序;api密钥
- 为Google Matrix指定API密钥API Javascript检索用法
- 谷歌云打印API密钥
- YouTube API密钥安全-我应该有多担心
- 使用javascript使用带有API密钥的API
- 您是否需要将 API 密钥用于客户端应用程序的谷歌地图 API
- 用于客户端-服务器通信和安全的 API 密钥
- 复制 API 密钥是否意味着身份被盗?
- 在 Javascript 中保护 API 密钥
- 是否可以检测到谷歌地图何时拒绝了API密钥
- 当我的 API 密钥位于 .gitignore 文件中时,如何从 git 部署到 heroku
- 在哪里使用地方 API 密钥
- 如何正确添加谷歌地图 api 密钥
- 谷歌地理编码仅在没有API密钥的情况下运行
- 在模型同步时发送带有 json 的 API 密钥
- Google 日历 API 密钥不允许通过简单的 GET 请求访问公共日历