Procedure to request a JSON file or an XML file in the local...

23
Procedure to request a JSON file or an XML file in the local host Using AJAX with JQuery Cross Domain File Request: Access Across Domains For security reasons, modern browsers do not allow access across domains. This means that both the web page and the XML file it tries to load, must be located on the same server. The examples on W3Schools all open XML files located on the W3Schools domain. If you want to use the example above on one of your own web pages, the XML files you load must be located on your own server. Same Domain File Request: With Google Chrome: Need a local Web Server to request a file using AJAX with JQuery on the local host For example, in order to host these pages locally, MAMP’s local server is set up and used. Using the local server is necessary because when introducing JQuery’s getJson function, you will encounter cross origin domain requests which are not allowed when not on a server. With Firefox: No need to set a local Web Server to request a file using AJAX with JQuery on the local host /*use the JQuery function $.getJSON() to simply grab a JSON data file*/ function getJSON(){ $.getJSON("YelpOneBusinessJasonData.json", function(result){ jsondata = result; processJson(jsondata); }); } /*set our corresponding html via our json objects*/

Transcript of Procedure to request a JSON file or an XML file in the local...

  • Procedure to request a JSON file or an XML file in the local host Using AJAX with

    JQuery

    Cross Domain File Request:

    Access Across Domains

    For security reasons, modern browsers do not allow access across domains.

    This means that both the web page and the XML file it tries to load, must be located on the same server.

    The examples on W3Schools all open XML files located on the W3Schools domain.

    If you want to use the example above on one of your own web pages, the XML files you load must be located on your own server.

    Same Domain File Request: With Google Chrome: Need a local Web Server to request a file using AJAX with JQuery on the local host

    For example, in order to host these pages locally, MAMP’s local server is set up and used. Using the local server is

    necessary because when introducing JQuery’s getJson function, you will encounter cross origin domain requests

    which are not allowed when not on a server.

    With Firefox: No need to set a local Web Server to request a file using AJAX with JQuery on the local host

    /*use the JQuery function $.getJSON() to simply grab a JSON data file*/

    function getJSON(){

    $.getJSON("YelpOneBusinessJasonData.json", function(result){

    jsondata = result;

    processJson(jsondata);

    });

    }

    /*set our corresponding html via our json objects*/

  • function processJson(data){

    //Set name first

    var name_html = document.getElementById('name');

    name_html.innerText = data.name;

    //Create our services and features table

    replacement_html = "";

    for(i in data.attributes){

    replacement_html += ""

    if(typeof data.attributes[i] == 'object'){

    var vals = Object.values(data.attributes[i]);

    var keys = Object.keys(data.attributes[i]);

    for(j in vals){

    if(vals[j] == true){

    replacement_html += "" + keys[j] + "";

    replacement_html += "";

    }

    }

    }else{

    if(data.attributes[i] == true){

    replacement_html += "" + i + "";

    replacement_html += "";

    }

  • }

    }

    replacement_html += "";

    var services_html = document.getElementById('services');

    services_html.innerHTML = replacement_html;

    }

  • For XML, Consider using jQuery.parseXML

    If you need to parse large XML documents that you may not be able to completely hold in memory,

    consider using a SAX style parser like this one: https://github.com/isaacs/sax-js/

    function getXML(){ 116. var xhttp = new XMLHttpRequest(); 117. xhttp.onreadystatechange = function(){ 118. if(this.readyState == 4 && this.status == 200){ 119. processXML(this); 120. }

    121. } 122. xhttp.open("GET", "restaurant_menu.xml", true); 123. xhttp.send();

    124. } 125.

    126. function processXML(data){ 127. var parser = new DOMParser(); 128. var xml = parser.parseFromString(data.responseText, "text/xml"); 129. 130. //Process breakfast

    131. var html = document.getElementById("breakfast"); 132. var tempHtml = tableCreator(xml, "BREAKFAST"); 133. html.innerHTML += tempHtml;

    134. 135. //Process brunch

    136. html = document.getElementById("brunch");

    137. tempHtml = tableCreator(xml, "BRUNCH"); 138. html.innerHTML += tempHtml;

    139.

    140. //Process lunch

    141. html = document.getElementById("lunch");

    142. tempHtml = tableCreator(xml, "LUNCH");

    143. html.innerHTML += tempHtml; 144.

    145. //Process dinner

    146. html = document.getElementById("dinner");

    147. tempHtml

    jQuery.parseXML( data )Returns: XMLDocument

    Description: Parses a string into an XML document.

    • version added: 1.5jQuery.parseXML( data )

  • o data

    Type: String

    a well-formed XML string to be parsed

    jQuery.parseXML uses the native parsing function of the browser to create a valid XML

    Document. This document can then be passed to jQuery to create a typical jQuery object

    that can be traversed and manipulated.

    Example:

    Create a jQuery object using an XML string and obtain the value of the title node.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    jQuery.parseXML demo

    var xml = "RSS Title",

    xmlDoc = $.parseXML( xml ),

    $xml = $( xmlDoc ),

    $title = $xml.find( "title" );

  • 16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    // Append "RSS Title" to #someElement

    $( "#someElement" ).append( $title.text() );

    // Change the title to "XML Title"

    $title.text( "XML Title" );

    // Append "XML Title" to #anotherElement

    $( "#anotherElement" ).append( $title.text() );

    jQuery.ajax( url [, settings ] )Returns: jqXHR

    Description: Perform an asynchronous HTTP (Ajax) request.

    • version added: 1.5jQuery.ajax( url [, settings ] )

    o url

    Type: String

    A string containing the URL to which the request is sent.

    o settings

    Type: PlainObject

    A set of key/value pairs that configure the Ajax request. All settings are optional. A

    default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for

    a complete list of all settings.

  • • version added: 1.0jQuery.ajax( [settings ] )

    o settings

    Type: PlainObject

    A set of key/value pairs that configure the Ajax request. All settings are optional. A

    default can be set for any option with $.ajaxSetup().

    � accepts (default: depends on DataType)

    Type: PlainObject

    A set of key/value pairs that map a given dataType to its MIME type, which gets sent in

    the Accept request header. This header tells the server what kind of response it will

    accept in return. For example, the following defines a custom type mycustomtype to be

    sent with the request:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    $.ajax({

    accepts: {

    mycustomtype: 'application/x-some-custom-type'

    },

    // Instructions for how to deserialize a `mycustomtype`

    converters: {

    'text mycustomtype': function(result) {

    // Do Stuff

    return newresult;

    }

    },

    // Expect a `mycustomtype` back from server

    dataType: 'mycustomtype'

    });

  • 16

    Note: You will need to specify a complementary entry for this type in converters for

    this to work properly.

    � async (default: true)

    Type: Boolean

    By default, all requests are sent asynchronously (i.e. this is set to true by default). If

    you need synchronous requests, set this option to false. Cross-domain requests and

    dataType: "jsonp" requests do not support synchronous operation. Note that

    synchronous requests may temporarily lock the browser, disabling any actions while

    the request is active. As of jQuery 1.8, the use of async: false with jqXHR

    ($.Deferred) is deprecated; you must use the success/error/complete callback options

    instead of the corresponding methods of the jqXHR object such as jqXHR.done().

    � beforeSend

    Type: Function( jqXHR jqXHR, PlainObject settings )

    A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x,

    XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The

    jqXHR and settings objects are passed as arguments. This is an Ajax Event.

    Returning false in the beforeSend function will cancel the request. As of jQuery 1.5,

    the beforeSend option will be called regardless of the type of request.

    � cache (default: true, false for dataType 'script' and 'jsonp')

    Type: Boolean

    If set to false, it will force requested pages not to be cached by the browser. Note:

    Setting cache to false will only work correctly with HEAD and GET requests. It works

    by appending "_={timestamp}" to the GET parameters. The parameter is not needed

    for other types of requests, except in IE8 when a POST is made to a URL that has

    already been requested by a GET.

    � complete

    Type: Function( jqXHR jqXHR, String textStatus )

    A function to be called when the request finishes (after success and error callbacks

    are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x,

    XMLHTTPRequest) object and a string categorizing the status of the request

    ("success", "notmodified", "nocontent", "error", "timeout", "abort", or

    "parsererror"). As of jQuery 1.5, the complete setting can accept an array of

    functions. Each function will be called in turn. This is an Ajax Event.

    � contents

    Type: PlainObject

    An object of string/regular-expression pairs that determine how jQuery will parse the

    response, given its content type. (version added: 1.5)

    � contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')

    Type: Boolean or String

  • When sending data to the server, use this content type. Default is "application/x-www-

    form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass

    in a content-type to $.ajax(), then it is always sent to the server (even if no data is

    sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type

    header. Note: The W3C XMLHttpRequest specification dictates that the charset is

    always UTF-8; specifying another charset will not force the browser to change the

    encoding. Note: For cross-domain requests, setting the content type to anything other

    than application/x-www-form-urlencoded, multipart/form-data, or text/plain will

    trigger the browser to send a preflight OPTIONS request to the server.

    � context

    Type: PlainObject

    This object will be the context of all Ajax-related callbacks. By default, the context is

    an object that represents the Ajax settings used in the call ($.ajaxSettings merged with

    the settings passed to $.ajax). For example, specifying a DOM element as the context

    will make that the context for the complete callback of a request, like so:

    1

    2

    3

    4

    5

    6

    $.ajax({

    url: "test.html",

    context: document.body

    }).done(function() {

    $( this ).addClass( "done" );

    });

    � converters (default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text

    xml": jQuery.parseXML})

    Type: PlainObject

    An object containing dataType-to-dataType converters. Each converter's value is a

    function that returns the transformed value of the response. (version added: 1.5)

    � crossDomain (default: false for same-domain requests, true for cross-domain requests)

    Type: Boolean

    If you wish to force a crossDomain request (such as JSONP) on the same domain,

    set the value of crossDomain to true. This allows, for example, server-side redirection

    to another domain. (version added: 1.5)

    � data

    � dataType (default: Intelligent Guess (xml, json, script, or html))

  • Type: String

    The type of data that you're expecting back from the server. If none is specified,

    jQuery will try to infer it based on the MIME type of the response (an XML MIME type

    will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the

    script, and anything else will be returned as a string). The available types (and the

    result passed as the first argument to your success callback) are:

    � "xml": Returns a XML document that can be processed via jQuery.

    � "html": Returns HTML as plain text; included script tags are evaluated when

    inserted in the DOM.

    � "script": Evaluates the response as JavaScript and returns it as plain text. Disables

    caching by appending a query string parameter, _=[TIMESTAMP], to the URL unless

    the cache option is set to true. Note: This will turn POSTs into GETs for remote-

    domain requests.

    � "json": Evaluates the response as JSON and returns a JavaScript object. Cross-

    domain "json" requests are converted to "jsonp" unless the request includes jsonp:

    false in its request options. The JSON data is parsed in a strict manner; any

    malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an

    empty response is also rejected; the server should return a response of null or {}

    instead. (See json.org for more information on proper JSON formatting.)

    � "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end

    of your URL to specify the callback. Disables caching by appending a query string

    parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.

    � "text": A plain text string.

    • multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType

    from what it received in the Content-Type header to what you require. For example,

    if you want a text response to be treated as XML, use "text xml" for the dataType. You

    can also make a JSONP request, have it received as text, and interpreted by jQuery

    as XML: "jsonp text xml". Similarly, a shorthand string such as "jsonp xml" will first

    attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and

    then from text to xml.

    • Sending Data to the Server

    By default, Ajax requests are sent using the GET HTTP method. If the POST method is

    required, the method can be specified by setting a value for the type option. This option

    affects how the contents of the data option are sent to the server. POST data will always be

    transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.

    The data option can contain either a query string of the form key1=value1&key2=value2, or an

    object of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is

    converted into a query string using jQuery.param() before it is sent. This processing can be

  • circumvented by setting processData to false. The processing might be undesirable if you

    wish to send an XML object to the server; in this case, change the contentType option from

    application/x-www-form-urlencoded to a more appropriate MIME type.

  • Examples:

    Save some data to the server and notify the user once it's complete.

    1

    2

    3

    4

    5

    6

    7

    8

    $.ajax({

    method: "POST",

    url: "some.php",

    data: { name: "John", location: "Boston" }

    })

    .done(function( msg ) {

    alert( "Data Saved: " + msg );

    });

    Retrieve the latest version of an HTML page.

    1

    2

    3

    4

    5

    6

    7

    $.ajax({

    url: "test.html",

    cache: false

    })

    .done(function( html ) {

    $( "#results" ).append( html );

    });

    Send an xml document as data to the server. By setting the processData option to false,

    the automatic conversion of data to strings is prevented.

  • 1

    2

    3

    4

    5

    6

    7

    8

    var xmlDocument = [create xml document];

    var xmlRequest = $.ajax({

    url: "page.php",

    processData: false,

    data: xmlDocument

    }); xmlRequest.done( handleResponse );

    Send an id as data to the server, save some data to the server, and notify the user once it's

    complete. If the request fails, alert the user.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    var menuId = $( "ul.nav" ).first().attr( "id" );

    var request = $.ajax({

    url: "script.php",

    method: "POST",

    data: { id : menuId },

    dataType: "html"

    }); request.done(function( msg ) {

    $( "#log" ).html( msg );

    }); request.fail(function( jqXHR, textStatus ) {

    alert( "Request failed: " + textStatus );

    });

  • Load and execute a JavaScript file.

    1

    2

    3

    4

    5

    $.ajax({

    method: "GET",

    url: "test.js",

    dataType: "script"

    });

    Problem:

    I'm working on a offline version of a website using jQuery and some xml files. I'm running in to a problem in jQuery when I do a $.ajax call on an xml file jQuery throws a error.

    When I look at the error I can tell its loading the XML file because its in the error's responceText property. It seems to work just fine in Firefox.

    This is how my call looks

    $.ajax({

    type: "GET",

    url: "Modules/" + ModuleID + "/ModuleContent.xml",

    dataType: "xml",

    success: function(x) { xml = x; ProcessXML(); },

    error: function(x) { alert(x.responceText); }

    });

    When I run this on a web server it works just fine. Its only when I run it from the file itself when

    I have this problem. How I can make this work in IE? Need to Covert

    http://api.jquery.com/jQuery.ajax/

    When loading XML files locally, e.g. a CD-ROM etc., the data received by Internet Explorer is plain-text, not text/xml. In this case, use the dataType parameter to load the xml file as text, and parse the returned data within the success function

    $.ajax({

    url: "data.xml",

    dataType: ($.browser.msie) ? "text" : "xml",

    success: function(data){

    var xml;

  • if (typeof data == "string") {

    xml = new ActiveXObject("Microsoft.XMLDOM");

    xml.async = false;

    xml.loadXML(data);

    } else {

    xml = data;

    }

    // Returned data available in object "xml"

    }

    });

    If you are planning to use NodeJS ,

    See The best node module for XML parsing . I've used xml-stream and it works pretty well. For a cross-browser solution: Cross-Browser Javascript XML Parsing .

    Regarding the 'talking to the browser', if in NodeJS, use fs module. Otherwise (browser), use the FileAPI (see https://scotch.io/tutorials/use-the-html5-file-api-to-work-with-files-locally-in-the-browser) and then the crossbrowser solution above.

    See the compatibility table for the FileAPI: http://caniuse.com/#feat=fileapi (all modern browsers)

    The best node module for XML parsing

    you can try with xml2js. Its a simple XML to JavaScript object converter. It gets your xml converted to js object so that you can access them with ease.

    Here are some other options

    1. libxmljs 2. xml-stream 3. xmldoc 4. cheerio – implements a subset of core jQuery for XML (and HTML)

    This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.

    So, which XML parsing module to pick?

    Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.

  • Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.

    Creating Hyperlinks to Files on the Local Hard Drive

    Problem: I am creating a report in LabVIEW and I would like to have a hyperlink that opens a file on the local hard drive. I can create a link to a webpage, but what is the URL syntax for a file on the local machine? Solution: The URL of a file on the local system is specified in the following format: file:///filepath/filename Where filepath is the full path to the location of your file (e.g. C:/temp/myfolder/) and filename is the name

    of the file (e.g. mydoc.txt). For example, the URL for a file called mydoc.txt located in the temp folder on the C: drive would be: file:///C:/temp/mydoc.txt If you are using the Report Generation Toolkit with LabVIEW, this URL is wired to the input of the Append Hypertext Link Anchor to Report.vi.

    Using HTML5 File API

    I recently came across a problem in a project that I was working on. I needed the user to be able to load an image into the browser, make a few edits to it, and then upload after they were pleased with the edits.

    A more old fashioned way of doing this would be to:

    • Upload your image via AJAX • Render the uploaded image in the browser • Make edits using JavaScript • Make another request with data on how to process the image and • Apply the changes on the server

    Two trips to the server? That seemed inefficient to me so I researched a little bit more and discovered the HTML5 File API.

  • # What is the HTML5 File API? The HTML5 File API allows you to create applications that let the user interact with files locally. Basically, you can load files and render them in the browser without actually having to upload the files.

    # 3 Main HTML5 File Objects There are three main objects that you need to know about to work with files locally:

    File – A single file object with some metadata

    FileList – Simply a list of file objects.

    FileReader – An object to read files with a number of methods and event handlers to interact with them.

    # Accessing A File Using JavaScript A file list can be accessed when you select a file using an HTML file input. Here is some sample code to handle file inputs. We will console.log() so that we can see what the input is providing us.

    Select a Single File

    // detect a change in a file input with an id of “the-file-input”

    $("#the-file-input").change(function() {

    // will log a FileList object, view gifs below

    console.log(this.files);

    });

    Selecting Multiple Files

  • # Rendering the File in Browser

    Now that we know how to access the FileList object, all that is left to do is to render the file in the browser. We do this by feeding one of the File objects into a FileReader to generate a local url that can be used as the src in an image element.

    // render the image in our view

    function renderImage(file) {

    // generate a new FileReader object

    var reader = new FileReader();

    // inject an image with the src url

    reader.onload = function(event) {

    the_url = event.target.result

    $('#some_container_div').html("")

    }

    // when the file is read it triggers the onload event above.

    reader.readAsDataURL(file);

    }

    // handle input changes

    $("#the-file-input").change(function() {

    console.log(this.files)

    // grab the first image in the FileList object and pass it to the function

    renderImage(this.files[0])

    });

    With this simple code, we are able to grab and display an image without a trip to the server! This is great since it lessens the load on our server when we have a giant amount of users uploading to our incredibly popular application.

    Cross-Browser Javascript XML Parsing

    Are there any cross-browser / cross-platform ways to parse XML files in Javascript?

    The following will work in all major browsers, including IE 6:

    var parseXml;

    if (typeof window.DOMParser != "undefined") {

    parseXml = function(xmlStr) {

  • return ( new window.DOMParser() ).parseFromString(xmlStr,

    "text/xml");

    };

    } else if (typeof window.ActiveXObject != "undefined" &&

    new window.ActiveXObject("Microsoft.XMLDOM")) {

    parseXml = function(xmlStr) {

    var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");

    xmlDoc.async = "false";

    xmlDoc.loadXML(xmlStr);

    return xmlDoc;

    };

    } else {

    throw new Error("No XML parser found");

    }

    Example usage:

    var xml = parseXml("Stuff");

    alert(xml.documentElement.nodeName);

    Live demo:

    http://jsfiddle.net/3s7Ly/1/

    Consider using jQuery.parseXML

    If you need to parse large XML documents that you may not be able to completely hold in memory,

    consider using a SAX style parser like this one: https://github.com/isaacs/sax-js/

    jQuery.parseXML( data )Returns: XMLDocument

    Description: Parses a string into an XML document.

    • version added: 1.5jQuery.parseXML( data )

    o data

    Type: String

    a well-formed XML string to be parsed

    jQuery.parseXML uses the native parsing function of the browser to create a valid XML

    Document. This document can then be passed to jQuery to create a typical jQuery object

    that can be traversed and manipulated.

    Example:

    Create a jQuery object using an XML string and obtain the value of the title node.

  • 1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    jQuery.parseXML demo

    var xml = "RSS Title",

    xmlDoc = $.parseXML( xml ),

    $xml = $( xmlDoc ),

    $title = $xml.find( "title" );

    // Append "RSS Title" to #someElement

    $( "#someElement" ).append( $title.text() );

    // Change the title to "XML Title"

    $title.text( "XML Title" );

  • 22

    23

    24

    25

    26

    27

    28

    29

    30

    // Append "XML Title" to #anotherElement

    $( "#anotherElement" ).append( $title.text() );

    Same-Origin Policy

    If you are developing a modern web-based application, chances are you:

    1. Are using javascript on the client side. 2. Need to integrate with services that are not completely under your control (or that reside in a

    different “origin”).

    3. Have been confronted by this error message in your browser’s console:

    XMLHttpRequest cannot load http://external.service/. No 'Access-Control-Allow-

    Origin' header is present on the requested resource. Origin 'http://my.app' is therefore not allowed access.

    Every time I need to integrate a web app with some external service or some server-side API I have no complete control over, I bump into this error. Google has not yet provided me with a concise description of the problem or an overview of alternatives to perform Cross-Domain requests, so this post will serve as a personal future reference.

    Same-Origin Policy

    We are seeing this error because we are violating something called the Same-Origin Policy (SOP). This is a security measure implemented in browsers to restrict interaction between documents (or scripts) that have different origins.

    The origin of a page is defined by its protocol, host and port number. For example, the origin of this page is (‘http’,’jvaneyck.wordpress.com’, 80). Resources with the same origin have full

  • access to each other. If pages A and B share the same origin, Javascript code included on A can perform HTTP requests to B’s server, manipulate the DOM of B or even read cookies set by B. Note that the origin is defined by the source location of the webpage. To clarify: a javascript source file loaded from another domain (e.g. a jQuery referenced from a remote CDN) will run in the origin of the HTML that includes the script, not in the domain where the javascript file originated from.

    For Cross-Origin HTTP requests in specific, the SOP prescribes the following general rule: Cross-Origin writes are allowed, Cross-Origin reads are not. This means that if A and C have a different origin, HTTP requests made by A will be received correctly by C (as these are “writes”), but the script residing in A will not be able to read any data -not even the response code- returned from C. This would be a Cross-Origin “read” and is blocked by the browser resulting in the error above. In other words, the SOP does not prevent attackers to write data to their origin, it only disallows them to read data from your domain (cookie, localStorage or other) or to do anything with a response received from their domain.

    The SOP is a Very Good Thing™. It prevents malicious script from reading data of your domain and sending it to their servers. This means that some script kiddie will not be able to steal your cookies that easily.

    Performing Cross-Domain requests

    Sometimes however, you have to consciously perform Cross-Domain requests. A heads up: This will require some extra work.

    Examples of legitimate Cross-Domain requests are:

    • You have to integrate with a third-party service (like a forum) that has a REST API residing in a

    different origin.

    • Your server-side services are hosted on different (sub)domains.

    • Your client-side logic is served from a different origin than your server-side service endpoints.

    • …

    Depending on the amount of control you have over the server-side, you have multiple options to enable Cross-Domain requests. The possible solutions I will discuss are: JSONP, the use of a server-side proxy and CORS.

    There are other alternatives, the most widely used being a technique using iframes and window.postMessage. I will not discuss it here, but for those interested an example can be found here.

    Example code

    I wrote some code to try out the different approaches discussed in this post. You can find the full code on my github. They should be easy to run locally if you want to experiment with them yourself. The examples each host 2 websites, a site in origin (‘http’, ‘localhost’, 3000) and one in

  • (‘http’, ‘localhost’, 3001). These are different origins, so requests from 3000 to 3001 are considered Cross-Domain requests and are blocked by the browser by default.