Our Engineers can Write as well

A guidepost on when and how to apply Cross origin Domain XMLHttpRequest

Over the years, JavaScript and Web programming have grown tremendously seeing several revisions and changes to suit modern day needs, yet ‘the same-origin policy‘ remains. The fundamental purpose of this policy is to prevent JavaScript from making requests across domain boundaries in the process instigating various hacks for making cross-domain requests.

Here’s where Cross-Origin Resource Sharing (CORS) helps. Web administrators, server developers and front-end developers are the likely lot who find this technology more useful when they need to access resources across domains, servers, protocol or port.

What exactly is CORS?

 

The Cross Origin Resource Sharing (CORS) is a spec developed by the World Wide Web Consortium (W3C), enabling secure cross-domain requests and data transfers between browser and webserver. Additional HTTP headers are used to gain permission to access resources from a different domain server, protocol or port than the one from which the current document originated. It is to be noted that, modern browsers to mitigate any risks during cross-origin HTTP request use XMLHttpRequest or Fetch.

In this blog, Future Focus discuss when and how to apply CORS XMLHTTPRequest.

When you execute a $http.post (or) $http.get service request and find the below error pop up on your console (Fig a), your cross domain request has certainly failed. Simple reason – the resources can’t be fetched as it’s available on a different server, different domain and different port.

xmlhttprequest

So how can you fix it? Declare the other domain IP address and use the following syntax.

Access-Control-Allow-Origin: 192.168.1.00:8080

You may see it works.

Also, use this syntax, for all domain access.

Access-Control-Allow-Origin: *

Here are some scenarios where CORS is used:
  • 1. By developers using CROS domain in SPA(single page application).

  • 2. In angular(2,4,5) or angularjs $routeProvider (or)$httpProvider

Let’s see how to use it:

Code:

(function () {

    ‘use strict’;

var app = angular.module(‘app’, [‘ngRoute’, ‘ngCookies’, ‘datatables’, ‘ui.bootstrap’, ‘ngMaterial’, ‘infinite-scroll’, ‘datatables.fixedheader’, ‘ngAnimate’, ‘ngSanitize’, ‘ngTable’])

.config(config)                   

config.$inject = [‘$routeProvider’, ‘$locationProvider’, ‘$httpProvider’];

function config($routeProvider, $locationProvider, $httpProvider) {

$routeProvider

.when(‘/’, {

controller: ‘homeController’,

templateUrl: ‘home/home.html’,

controllerAs: ‘vm’,

css: ‘dashboard.css’

})

.when(‘/login’, {

controller: ‘indexController’,

templateUrl: ‘index/index.html’,

controllerAs: ‘vm’,

})

.otherwise({ redirectTo: ‘/login’ });

$httpProvider.defaults.useXDomain = true;

$httpProvider.defaults.headers.common = {};

$httpProvider.defaults.headers.common[‘Access-Control-Allow-Origin’] = ‘*’;

$httpProvider.defaults.headers.post[‘Access-Control-Allow-Origin’] = ‘*’;

$httpProvider.defaults.headers.put = {};

$httpProvider.defaults.headers.patch = {};

delete $httpProvider.defaults.headers.common[‘X-Requested-With’];

}          

})();

CROSS-ORIGIN RESOURCE SHARING DIAGRAM:

This is a pictorial representation illustrating how a web server interact with another server to determine whether to allow a web page to access a resource from different origin or not.

xml http request

Advantage of CORS:

  • CORS can be implemented in most of the modern browsers (Internet Explorer 8+, Firefox 3.5+, Safari 4+ and Chrome.)

  • It helps in lightweight development as frontend and backend running on different servers is made possible.

  • CORS also works on independent web services to cooperate and share resources.

Hope you find this brief blog post useful and informative.

For more such information, keep watching this space.

Lakshmi Narayanan - Software Engineer

Contributed by:

Lakshmi Narayanan
Software Engineer

Your email address will not be published. Required fields are marked *