Skip to content

Instantly share code, notes, and snippets.

@Wallsays
Created December 10, 2015 16:17
Show Gist options
  • Select an option

  • Save Wallsays/ecea0528c40d8d252e13 to your computer and use it in GitHub Desktop.

Select an option

Save Wallsays/ecea0528c40d8d252e13 to your computer and use it in GitHub Desktop.

Revisions

  1. Wallsays created this gist Dec 10, 2015.
    49 changes: 49 additions & 0 deletions test_cors.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    # Create the XHR object.
    createCORSRequest = (method, url) ->
    xhr = new XMLHttpRequest
    if 'withCredentials' of xhr
    # XHR for Chrome/Firefox/Opera/Safari.
    xhr.open method, url, true
    else if typeof XDomainRequest != 'undefined'
    # XDomainRequest for IE.
    xhr = new XDomainRequest
    xhr.open method, url
    else
    # CORS not supported.
    xhr = null
    xhr

    # Helper method to parse the title tag from the response.

    getTitle = (text) ->
    text.match('<title>(.*)?</title>')[1]

    # Make the actual CORS request.

    makeCorsRequest = ->
    # All HTML5 Rocks properties support CORS.
    url = 'http://updates.html5rocks.com'
    xhr = createCORSRequest('GET', url)
    if !xhr
    alert 'CORS not supported'
    return
    # Response handlers.

    xhr.onload = ->
    text = xhr.responseText
    title = getTitle(text)
    alert 'Response from CORS request to ' + url + ': ' + title
    return

    xhr.onerror = ->
    alert 'Woops, there was an error making the request.'
    return

    xhr.send()
    return

    url = 'http://localhost:3000/api/v1/qualifications'
    xhr = createCORSRequest('options', url)
    console.log( xhr.send() )