Nginx Reverse proxy for cross domains

Aug 24, 2020

A reverse proxy is a server that sits in front of web servers and forwards client request to those web servers.

Use case: If we try to access URL http://example.com:8080/api from webpage at http://example.com due to browser cross domain restrictions we will see CORS errors.

To solve, we can setup Nginx reverse proxy server, so that , we can request URL http://example.com/api from webpage at http://example.com and the reverse proxy server would take care of forwarding the request to server running at port 8080.

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    location /api {
        proxy_set_header HOST $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_pass http://127.0.0.1:8080;
    }
}

To pass a request to an HTTP proxied server, the proxy_pass directive is specified inside a location.

  • $host - This variable is set, in order of preference to: the host name from the request line itself, the “Host” header from the client request, or the server name matching the request.
  • $scheme - The schema of the original request.
  • X-Forwarded-Proto - header gives the proxied server information on the schema of the original request.
  • X-Real-IP - It is set to the IP address of the client.
  • $proxy_add_x_forwarded_for - This variable takes the value of original X-Forwarded-For header retrieved from the client and adds the Nginx server IP address to the end.

References:

Categories : HTTP

JavaScript Object

Aug 24, 2020

An object is a collection of properties. A property is a associate between a name and a value.

for...in can be used to iterate over all the enumerable properties of an object.

var myFan = {
    make: 'Honeywell',
    blades: 4,
    rotation: 'on'
}

for (var i in myFan) {
    if (myFan.hasOwnProperty(i)) {
        console.log(i + " :: " + myFan[i]);
    }
}
// outputs
// make :: Honeywell
// blades :: 4
// rotation :: on

Ways to create objects

Object initializers

var rectangle = {width: 10, height: 100};

Constructor function

function TV(make, model) {
    this.make = make;
    this.model = model;
}

var myTv = new TV('LG', 'ThinQ');

Object.create

Allows to choose the prototype object for the object you want to create, without having to define a constructor function.

var bike = {
    wheels : 2,
    gear: 6
}
var myBike = Object.create(bike);

References:

Categories : JavaScript

JavaScript Array

Aug 20, 2020

An array is an ordered list of values that you refer to with a name and an index. JavaScript does not have a explicity array data type. JavaScript provides predefined Array object and methods to work with arrays.

let arr1 = new Array(1, 2, 3, 4, 5);
let arr2 = ['a', 'b', 'c']; // Bracket sytax is called an "array literal"

let arr3 = new Array(10); //creates array with non zero length, but without any items.

let arr4 = Array.of(10); //creates a array with only one element. Array.of a static method in ES2015

Iterating over arrays

let myarr = [1, 2, 3, 4, 5];
for(let i = 0; i < myarr.length; i++) {
    console.log(myarr[i]); // 1, 2, 3, 4, 5
}

myarr.forEach(function(item) {
    console.log(item); // 1, 2, 3, 4, 5
});

Array methods

  • concat() - joins two or more arrays and returns a new array.
  • join() - joins all elements of an array into a string.
  • push() - adds one or more elements to the end of an array and returns the length of the array.
  • pop() - removes the last element from the array and returns the element.
  • shift() - removes the first element from the array and returns the element.
  • unshift() - adds one or elements to the front of the array and returns the new length of the array.
  • slice() - extracts a section of the array returns a new array.
  • splice() - removes elements from an array and optionally replaces them. It returns the items that were removed from the array.
  • reverse() - transposes the elements of the array.
  • sort() - sorts the elements of the array in place.
  • indexOf() - searches the array for the search element and returns the index of first match.
  • lastIndexOf() - searches backward and works like indexOf()
  • forEach() - executes a callback on every array item.
  • map() - executes a callback on every item and returns a new array of the return value of the callback.
  • filter() - executes a callback on every item and returns a new array containing the items for which callback returned true.
  • every() - executes a callback on every item and returns true if callback returns true for every item.
  • some() - executes a callback on every item and returns true if callback returns true for some item.
  • reduce() - executes a callback on every item for the purpose of reducing the list of items down to single value.
  • reduceRight() - works like reduce() but starts with the last element.

References:

Categories : JavaScript

CORS - Cross-origin resource sharing

Aug 17, 2020

CORS is a mechanism that use additional HTTP headers to tell browser to give web application running at one origin access to selected resources from a different origin.

Same-origin policy prevents JavaScript from making requests across domain boundaries. Two URLs have the same origin if the protocol, port and host are the same for both

A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (protocol, post or host) from its own.

Preflight request

For HTTP request methods than can cause side effects on server data, CORS specification mandates that browser make “preflight” request. Preflight request is made with HTTP OPTIONS request method and upon approval from server send the actual request.

Simple requests

Simple requests are GET or POST with no custom headers and whose body is text/plain, the request is sent with an extra header ORIGIN. The ORIGIN header contains origin (protocol, post or host) of the requesting page. If the server decides to allow the request it sends a Access-Control-Alow-Origin header sending back same origin or * if its a public resource.

Request with credentials

By default cross domain requests will not send credentials (cookies etc.). With property withCredentials set to true on XMLHTTPRequest , the credentials can be sent in the request. But the browser will reject the response if response doesn’t have Access-Control-Allow-Credentials: true.

References

Categories : JavaScript   HTTP

JavaScript Collections

Aug 13, 2020

ECMAScript2015(ES6) introduced four new collections Map, Set, WeakMap and WeakSet.

Map

A Map object is a simple key/value map and can iterate its elements in insertion order.

let barMap = new Map();
barMap.set('one', 1);
barMap.set('two', 2);
barMap.set('three', 3);

for (let [key, value] of barMap) {
    console.log(key + ' = ' + value); // one = 1, two = 2, three = 3
}

barMap.forEach(function(value, key) {
    console.log(key + ' = ' + value); // one = 1, two = 2, three = 3
});

Set

A Set object is a collection of values. A value in a set may only occur once. You can iterate its elements in insertion order.

let bazSet = new Set();
bazSet.add('a');
bazSet.add('b');
bazSet.add('c');

for (let value of bazSet) {
    console.log(value); // a, b, c
}

WeakMap

A WeakMap is a collection of key/value pairs in which the keys are weakly referenced. The keys must be objects. They allow for objects which are no longer needed to be cleared from memory. There is no method to obtain a list of the keys.

const foowm = new WeakMap();
const key1 = {};
foowm.set(key1, "value1");
foowm.get(key1); // "value1"

WeakSet

A WeakSet is a collection of objects. References to objects are held weakly. If no other references to an object stored in the WeakSet exist , those objects can be garbage collected.

const barws = new WeakSet();
const value1 = {};
barws.add(value1);

References

Categories : JavaScript   ES6