nreddy216 nreddy216 - 6 months ago 22
AngularJS Question

How do I use an environmental variable within my AngularJS controller?

I included my API Key in my '.env' file which is hidden from Git.

In .env file

API_TOKEN=secrettokengibberish


Within my Angular controller, I want to access this variable when making my AJAX call.

In StoryController.js

var apiEndpoint = 'https://someapi.com/'+ $scope.myQuery +'.json?access_token=' + process.env.API_TOKEN;


The error that I keep getting when I do this is: process is not defined at StoryController

NOTE: I'm still learning Angular, so I'm not sure if this is even the right way to go about using API keys. Any advice is appreciated.

Answer

Here is what I think you're trying to do:

+----------+         +---------+
|          | ---1--> |         |
| Frontend | <--2--- | Backend |
|          |         |         |
+----------+         +---------+
    |   A
    |   |           +-----+
    |   |           |     |
    |   \----4------| API |
    \----3--------->|     |
                    +-----+

Here is what you should be doing:

+----------+         +---------+         +-----+
|          | ---1--> |         | ---2--> |     |
| Frontend | <--4--- | Backend | <--3--- | API |
|          |         |         |         |     |
+----------+         +---------+         +-----+

Normally, you don't want your token to be publicly available in your frontend.

Consider creating a endpoint in your own backend and making it access the API instead of your frontend.


Edit:

You do exactly as you'd be doing calling directly the API, but instead, you create this endpoint within your NodeJS backend. You'd probably want to use some framework like express (this is just an example):

var http = require('http');
var express = require('express');
var app = express();

app.get('/:myQuery', function (req, res) {
    var apiEndpoint = 'https://someapi.com/'+ req.params.myQuery +'.json?access_token=' + process.env.API_TOKEN;
    http.get(apiEndpoint, function(apiResponse) {
        apiResponse.setEncoding('utf8');
        res.status(apiResponse.statusCode);
        apiResponse.on('data', function (chunk) {
           console.log('BODY: ' + chunk);
           res.json(JSON.parse(chunk);
        });
    });
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

Then, in your frontend, your angular controller would do something like:

$http.get('http://localhost:3000/+' + $scope.myQuery).then(function(){
   //...
});
Comments