Category Archives: Yeoman

AngularJS custom HTTP headers in resource service

Recently i had to make an HTTP call from the browser (client-side) using JavaScript / AngularJS to a REST API (server-side) and retrieve data. Since the authentication mechanism of the API required a security token to be passed over with the request, i studied AngularJS specs on how to do it best. Basically, there are two ways to do it, either as a:

  1. query parameter, or
  2. custom HTTP header

 

Because i didn’t wanted the security token to appear anywhere in the logs or debugging console (like on the picture below, in case of making use of option 1 just mentioned, ie. query parameter), i decided on passing the token as a custom (there’s no standard header for passing tokens) HTTP header.

AngularJS query API token

 

Since i use Yeoman (app workflow/scaffolding tool) i noticed that through a standard angular-template used for generating an application scaffolding, you’re getting dependency on angular framework in version 1.0.7 (last stable version as of writing this post). Although this is what you would generally expect (stable version, not a snapshot), the problem is that angular documentation for $resource service (which is what i prefer to use over $http service), does not mention the possibility of sending HTTP headers (regarding $http – i think of it as a solution for rather “general purpose AJAX calls”).

 

One way to set HTTP headers is by accessing $httpProvider.defaults.headers configuration object, like this:

$httpProvider.defaults.headers.get['API-Token'] = 'vy4eUCqpQmGoeWsnHKwCQw'

(more documentation about that you’ll find here), but this way you’re modifying $httpProvider globally which may not be what you exactly want.

 

Google search came with help and i found issue 736, which acknowledges that “$resource should support custom http headers”, but it is with the (unstable) release 1.1.3 where this feature is supported for sure (maybe earlier “unstable” versions do support it too, haven’t checked that actually, but definitely none of the stable versions do, as of today).

 

So, what is it that you have to do in order to introduce an unstable version of AngularJS into your project managed by Bower?

bower install angular-unstable
bower install angular-resource-unstable

(dependency on angular-resource.js is required in order for it to work).

 

Now, the only other thing left to do is to update your index.html file accordingly (to make use of proper version of libraries) :

<script src="bower_components/angular-unstable/angular.js"></script>
<script src="bower_components/angular-resource-unstable/angular-resource.js"></script>

 

…and you can start adding custom HTTP headers in your code:

angular.module('usersService', ['ngResource'])
    .factory('User', function($resource, api-token) {
        var User = $resource('http://api.test.com\\:8080/1.0/users', { }, {
            query: {
                method: 'GET',
                isArray: true,
                headers: { 'API-Token': api-token }
            }
        });
        return User
    });

 

Hope this short post will save some of your time 🙂 Cheers!

 

 

Resources:

Advertisements

Yeoman, Karma and e2e testing

Imagine my surprise when i first looked at the Gruntfile.js of my newly generated angular app and found out that Yeoman is configuring by default only the karma:unit section, missing out the karma:e2e piece. I know the product is fairly new, but i would expect it to be a little more “mature” (spent quite some time figuring out why my e2e tests aren’t working and how to solve the problem).

 

Anyway, in order to run your e2e tests, you have to do the following:

  1. Update the Gruntfile.js
karma: {
    e2e: {
        configFile: 'karma-e2e.conf.js'
    },
    unit: { ... }
},
  1. Update the karma-e2e.conf.js
urlRoot = '/e2e/';
proxies = {
    // port has to be the same your web server is running on
    '/': 'http://localhost:9000'
};

 

Also, if you want Grunt to run your e2e tests without the need to manually run the web server first, you can additionally define the following task:

grunt.registerTask('test:e2e', function () {
    grunt.task.run([
        'clean:server',
        'concurrent:server',
        'connect:livereload',
        'open',
        'karma:e2e'
    ]);
});

 

(and “test:unit” task accordingly, for consistency sake):

grunt.registerTask('test:unit', [
    'karma:unit'
]);

JavaScript Toolset

Below you’ll find a short list specifying toolset that may be helpful when developing JavaScript code:

  1. Node.js – a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.
  2. NPM – node package manager (part of Node.js)
  3. Yeoman – a robust and opinionated client-side stack, comprising tools and frameworks that can help developers quickly build web applications
  4. Bower – package manager for javascript libraries
  5. Karma – Spectacular Test Runner for JavaScript
  6. WebStorm – The smartest JavaScript IDE
  7. Jasmine – a behavior-driven development (BDD) framework that allows writing specifications that denote how your code should behave.
  8. Batarang – Extends Chrome’s Developer Tools, adding tools for debugging and profiling AngularJS application
  9. RequireJS – a JavaScript file and module loader

 

Also, there are tools you’ll be using less frequently (especially, if you decide to go with Yeoman as Yo integrates many of them), but still it’s good to know what they do:

  1. angular-seed – seed project (an application skeleton) for angular apps. You can use it to quickly bootstrap your angular webapp projects and dev environment for these projects. The seed contains AngularJS libraries, test libraries and a bunch of scripts all pre-configured for instant web development gratification. Just clone the repo (or download the zip/tarball), start up our/provided (or yours) webserver and you are ready to develop and test your application.
  2. underscore.js – a utility-belt library for JavaScript that provides a lot of the functional programming support for the usual functional suspects (each, map, reduce, filter…) without extending any core JavaScript objects.
  3. angular-mocks.js – contains an implementation of mocks that makes testing angular apps easier.
  4. angular-scenario.js – a nifty JavaScript lib that allows you to write and execute end-to-end tests for angular applications
  5. angular-loader.js – module loader for Angular modules. If you are loading multiple script files containing Angular modules, you can load them asynchronosuly and in any order as long as you load this file first.
  6. angular-resource.js – provides $resource service that makes it possible to execute HTTP calls (eg. against REST API’s)
  7. angular-cookies.js – provides two services: $cookies and $cookieStore.
  8. angular-sanitize.js – provides ngBindHtml directive, linky filter and $sanitize service.