How to call a file in controller - javascript

I have a file in which ii declared my videouploadfolder url and i want to call that file in my js
my config.js
var filepath = {
uploadVideoUrl : './public/videos'
}
I called it in my node.js as
var config = require(config);
config.uploadVideoUrl;
But i am not sure how to call in js,can anyone suggest help please.Thanks.

With angularjs you can make use of constant,
var app = angular.module('configuration', [])
.constant('uploadVideoUrl', './public/videos')
Then you can use in your controller as,
app.controller('Ctrl1', ['$scope','uploadVideoUrl'
function ($scope,'uploadVideoUrl') {
var config = uploadVideoUrl;
}
]);

If you want your config.js file to stay only in server where you have ther services editing it, then you would have to write a REST route in nodeJs to fetch the content of the config and send it back to angularJS client.
If you dont mind saving that config json in your client side itself instead of your server then follow what Sajeetharan has said.

Related

Best way to secure an API key in Vanilla JS and Django

I am building a simple webapp in Django which makes use of Google Places API. The API is called from main.js file, and the data is displayed on the page.
Right now, the main.js file looks like this:
...
const apikey_gmaps = "AIzaSyDMjUwEt0bumPTVt1GpfQHrxyz";
var lat = position.coords.latitude;
var long = position.coords.longitude;
fetch("https://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&key="+**apikey_gmaps**)
.then(...
...
I want to secure the API key, since I don't want everyone to be use and share my credentials, and break my bank. I have been reading about it lately, and I am able to use .env file in Django(Python) using the Decouple library. I want to use the .env variables in the main.js file. The only solution that I could find was to use dotenv, but that requires NodeJS.
Is there any way to pass the API key from .env to Django and then from Django to main.js? Is there a better way of achieving this?
You can't secure it if you are calling it from the client-side. What you need to do is create a view to abstract the key.
In views.py:
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer
from rest_framework.response import Response
import requests
#api_view(('GET',))
#renderer_classes([JSONRenderer])
def gmapAPI(request):
lat = request.GET.get('lat', 'default_fb_value')
long = request.GET.get('long', 'default_fb_value')
apikey_gmaps = "#KEY_OR_GET_FROM_ENV";
url = f'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={lat},{long}&rankby=distance&key={apikey_gmaps}'
r = requests.get(url)
print(r.json())
return Response(r.json())
In urls.py add:
...
path('maps_api/', views.gmapAPI, name='maps_api'),
...
In main.js:
...
var lat = position.coords.latitude;
var long = position.coords.longitude;
var targetUrl = (`website/maps_api/?lat=${lat}&long=${long}`)
fetch(targetUrl)
.then(...
...
Please note that this will make the process of digging up the key very difficult, but the key will still be discoverable, and a good/bad hacker can still get it.

passing array of image objects to the jade and then displaying via jade

Here, I have use.js and use.jade.
In use.js, I am simply mapping hardcoded image variable img_01 from jade to use.js by specifying var $image= $(pclass + 'img_01');
In .js, I am assigning $image by some useful image using
$image.attr('src', useful_image)
Using img.use--img_01 in .jade, I am able to display the image (useful_image).
Now, my constraint is I don't want to hard code in .jade and let .jade display images as many as provided by .js.
So, I am able to create the array in .js of var $image=[] and then $image.push($(pclass + 'img_' + N.toString()) where N varies from 0 to K (lets say K =3).
Now I want to call these img_0, img_1, img_2 .....img_K in .jade and display them on page.
So my specific question is I am not able to iterate [img_0, img_1, img_2 .....img_K] in .jade. Can anyone tell what could be best method to do so????
Pls note: I used rendering method. For the same I used
var express = require('express');
var app = express();
But, node.js gets crashed with this itself leave aside using app.get...
You can pass object from server to client in this way.
app.get(..., function (req, res) {
var stats = { ... };
res.render('chart', { images: $arrImage });
});
For looping at client ,you can use jade#each.
each oneImage in images
img( src=oneImage.image)
Note : Jade is depricated,So try to use Pug#each

Unable to fetch list of files from back-end to front-end angular select options?

I am getting files from directory('.public/jsonfiles') in server.js file using node.js. But I am failing to get these list of files to show on my view page using AngularJS with my Node.js service.
Error:
I am getting data.forEach is not a function error(I can see total html content in the console instead of my list of files in my service file on return statement: return $http.get('/public/jsonfiles');
Otherwise if I give: return $http.get('').then(function(data){ console.log(data)}); /giving Main.get() success is not a function and giving total of html content on console
Created repository.
I had a look at your repo. On the request
return $http.get('/public/jsonfiles');
node will return index.html which will then make MainCtrl error on data.forEach as data is not an array.
If you install serve-index and use it to provide directory listing for public it should work.
var serveIndex = require('serve-index');
app.use('/public',serveIndex('public'));
(server.js)
To load the file json add another method to the MainService to get the file.
getFile: function (filename) {
//no public in the path because node is removing when it serves static files
return $http.get('/jsonfiles/' + filename);
}
In MainCtrl you can the load the file contents when the selected file is changed.
$scope.optionChanged = function () {
Main.getFile( $scope.selectedjsoncontent )
.success(function(result){
$scope.textAreaData = result;
});
}

Serve dynamic javascript file with nodejs

Questions
How to serve javascript file dynamically? Specifically, the scripts maintain most of its body but with some variables changable (imagine HTML Jade template, but this is for pure javascript).
Scenario
When user or browser (http GET in general) visits /file.js passing parameter api, e.g. /file.js?api=123456, I would like to output pure javascript where I can take that 123456 and put in inside of my code, dynamically. Content-Type is application/javascript.
Sample:
var api = #{req.query.api}; //Pseudo
//The rest of my javascripts template
...
From my main .js file, I have set up the route:
app.get( '/file.js', function( req, res ) {
//Pseudo code that I would like to achieve
var name = req.query.name;
res.render( 'out_put_javascript_file_from_jade_file.jade', { name: name } );
});
So when a person visits /file.js, the script file will be rendered differently based on the parameter api passed in the URL. The only possible dynamic way I can think of is using Jade, but it doesn't allow pure javascript template. I believe there must be other solutions.
Please excuse my explanation. The problem is somewhat like this: How to generate a pure JavaScript file with Jade
If you want to do something quick and dirty, then you can do something like this (based on your example in the comments).
App init - read the .js template file and cache it:
// this should be async, but hey, not teaching you that part here yet
var fileJs = fs.readFileSync('file.js.template');
File.js:
(function() {
$(window).on('load', function() {
alert('Your api key is API_KEY_CONST');
});
})();
Request:
GET /api/file.js?key=123
Router:
app.get('/api/file.js', function(req, res) {
var key = req.query.key;
var key = fetchKeyFromDBSync(); // just to make it easier here, no async.
var out = fileJs.replace(API_KEY_CONST, key);
res.setHeader('content-type', 'text/javascript');
res.write(out);
res.end();
});
Now, this is really dumb and you should not try it at home, but it simply demonstrates how to do what you wanted.
Edit:
Depending on the file length, you might perform a bit better if you put the chunks of the file into an array, like:
var fileChunks = ['(function(){ blablabla;', 'var myAPIKey=', 'KEY_PLACEHOLDER', '; alert (myAPIKey);', '})()']
So later when you're resolving it with the real API key, you join the file.
fileChunks[2] = '12345';
var responseData = fileChunks.join('');
res.write(responseData);
But your last-accessed api key is then held in an array. Not quite future proof, but it shouls work if you need something quick.

How to connect and put in JSON instead of mongolab in AngularJS?

I want to use JSON instead of MongoLab example shown on AngularJS website.
Here's the code from the website:
angular.module('mongolab', ['ngResource']).
factory('Project', function($resource) {
var Project = $resource('https://api.mongolab.com/api/1/databases' +
'/angularjs/collections/projects/:id',
{ apiKey: '4f847ad3e4b08a2eed5f3b54' }, {
update: { method: 'PUT' }
}
);
Is there any way I could connect and put into JSON file available on my folder instead of hosting it to MongoLab?
Any response would be really appreciated!
You can look at this example:
Reading in JSON through Angular Resources Service
You want to return the Project variable from your factory
var Project = $resource('test.json', {} );
return Project;
then use it in the controller after you inject it:
Project.get(function(data){
$scope.bar = data.foo;
});
Update:
After looking thru the 1.1.3 angular-resource.js code, it looks like it always does an http request to get its data. Set up a simple RoR app with a REST interface for testing.
Or use plunker (like the linked question above) for complete remote testing.

Categories

Resources