如何在响应 Angular 客户端应用时发送 API 密钥

How do I send an API key in a response to an Angular client app?

本文关键字:API 密钥 应用 客户端 响应 Angular      更新时间:2023-09-26

我正在尝试使用 $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}}&deg;<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'
    }
  })
})