JSON - CORS Issue

newklear

Expert Member
Joined
Apr 15, 2008
Messages
1,820
Reaction score
809
Location
Cape Town
Hello All

As title reads, I have a JSON url that I am trying to access using the POST method.

When I run a test using an Html page with supplied url I receive the CORS error, when I change this url to the supplied proxy I receive "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied", which indicates I am still breaking the Same origin policy. I did report this CORS error in the past and was recently given the proxy which was told would bypass this CORS issue.

However when I use The Firefox addon "Poster" for example, I see returning data based on what I send.

Factors:
  1. Can only make use of Javascript
  2. No use of JQuery

Are there any workarounds using only Javascript to this please ?

My Current Test Javascript code

Code:
<!DOCTYPE html>
<html>

<script>

//var url = "http://alternate.business.url";
var url = "/SuppliedProxy";
var getJSON = function(url) {
    return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open('post', url, true);
        xhr.responseType = 'json';
        xhr.onload = function() {
            var status = xhr.status;
            if (status == 200) {
                resolve(xhr.response);
            } else {
                reject(status);
            }
        };
        xhr.send();
    });
};

//getJSON('url').then(function(data) {
getJSON(url);
'"typeHint":"person",' +
'"firstName":"' + 'TestName' + '"';
console.log(getJSON);
</script>

</html>

Thank You for any input, greatly appreciated.
 
what "Access-Control-Allow-*" headers are the endpoints returning?
 
Any real reason why you can't use jquery? It has something for doing this.
 
what "Access-Control-Allow-*" headers are the endpoints returning?

Hello _kabal_

Here we go, please see below:

RESPONSE HEADERS

Content-Encoding
gzip
Content-Type
application/json
Date
Mon, 15 Aug 2016 12:42:05 GMT
Server
Apache-Coyote/1.1
Transfer-Encoding
chunked
Vary
Accept-Encoding



REQUEST HEADERS

POST /alternate.business.url HTTP/1.1

Host: business.url:38080

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: en-US,en;q=0.5

Accept-Encoding: gzip, deflate

origin: null

Connection: keep-alive

Cache-Control: max-age=0

Content-Length: 0
 
Any real reason why you can't use jquery? It has something for doing this.

Hi xumwun

I am just testing in html at the moment, at the end of the day this will go into an older version of Cisco Prime Service Catalogue that is not supported by any newer plugins.
 

Hi Thor187

Thank You for the share!, jee whizz that is a real neat cheat, unfortunately not working because of httpOnly:

500 Internal Server Error
690ms

HeadersPostXMLCookies
view source
Access-Control-Allow-Orig...
*
Content-Length
0
Date
Mon, 15 Aug 2016 13:05:26 GMT
Expires
Tue, 16 Aug 2016 13:05:25 GMT
Server
cloudflare-nginx
Set-Cookie
__cfduid=dcb2b3ffd183d9d6d68067a85b3da854e1471266325; expires=Tue, 15-Aug-17 13:05:25 GMT; path=/; domain
=.crossorigin.me; HttpOnly
X-Firefox-Spdy
h2
access-control-allow-cred...
false
access-control-allow-head...
Content-Type
cf-ray
2d2cdba69f043608-LHR

Thank You very much Thor187, that's the closest I have been in awhile, anything else I could try perhaps ?
 
Shot in the dark

HTML:
/**
 * Make a X-Domain request to url and callback.
 *
 * @param url {String}
 * @param method {String} HTTP verb ('GET', 'POST', 'DELETE', etc.)
 * @param data {String} request body
 * @param callback {Function} to callback on completion
 * @param errback {Function} to callback on error
 */
function xdr(url, method, data, callback, errback) {
    var req;
    
    if(XMLHttpRequest) {
        req = new XMLHttpRequest();

        if('withCredentials' in req) {
            req.open(method, url, true);
            req.onerror = errback;
            req.onreadystatechange = function() {
                if (req.readyState === 4) {
                    if (req.status >= 200 && req.status < 400) {
                        callback(req.responseText);
                    } else {
                        errback(new Error('Response returned with non-OK status'));
                    }
                }
            };
            req.send(data);
        }
    } else if(XDomainRequest) {
        req = new XDomainRequest();
        req.open(method, url);
        req.onerror = errback;
        req.onload = function() {
            callback(req.responseText);
        };
        req.send(data);
    } else {
        errback(new Error('CORS not supported'));
    }
}
 
Is the other API yours?

I unfortunately do not have access to server side. I have come across a few CORS fixes but they all point to server related fixes. A proxy was setup by one of the Java Dev's and he said it will sort the issue out.

This is where I am stuck, making use of Firefox's Poster I can pull what data I want with no issue. When I jump to an html page for testing I start seeing these CORS related errors again. At the end of the day if I can get a simple html page to function with JS I know I can dump the JS onto CPSC (Cisco Prime Service Catalogue) and my job is done.
 
I unfortunately do not have access to server side. I have come across a few CORS fixes but they all point to server related fixes. A proxy was setup by one of the Java Dev's and he said it will sort the issue out.

This is where I am stuck, making use of Firefox's Poster I can pull what data I want with no issue. When I jump to an html page for testing I start seeing these CORS related errors again. At the end of the day if I can get a simple html page to function with JS I know I can dump the JS onto CPSC (Cisco Prime Service Catalogue) and my job is done.
This is a security thing. Someone will come along and explain it better, since I'm on mobile. But basically a website cannot access an API it doesn't have access to, but an app will be fine.

If the endpoint was on the same domain as your html page, you wouldn't have an issue.
 
As mentioned above, you can't get around this without being able to set the response headers on the remote server. A work around is creating your own "proxy" script. So your JS script will make a request to your own server, and with whatever server side scripting you use, it will take in the parameters and call the remote server and then pass back whatever it receives.
 
if there are no Access-Control-Allow-* headers, the browser will not allow the request.

you basically need the following

Code:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Methods:POST, GET, PUT, OPTIONS, DELETE
Access-Control-Allow-Origin: *
OR
Access-Control-Allow-Origin: http://your-domain
Access-Control-Max-Age:3600


otherwise, as Denouncer said, you need to build a proxy.

CORS is enforced by the browser, not the server
 
Thank You DA-LION-619, Denouncer and _kabal_ for your input.

However my situation is that, I VPN into a secure layer so I can access the CPSC via a browser but do not have RDP access. I have been given a proxy to use which I have been alternating as:
Code:
 //var url = "http://alternate.business.url";
var url = "/SuppliedProxy/";
.

When using the normal business url: I receive CORS errors, when I make use of the supplied proxy, I receive NS_ERROR_DOM_BAD_URI: Access to restricted URI denied which with a quick google indicates I need to have index.html, script.js, db.mdf, db.ldf, db.ndf and data.jso etc. all in the same directory.

At this stage, I do not see any errors on the CPSC when running the JS, there is just no result as expected. I brought the test to an html page and picked up errors as above. When I run FireFox's 'Poster' I can pull exactly what I need in Json format but that doesn't help me get the necessary data into the CPSC.

I presume to move forward at this stage with the installed proxy, I would need to arrange index.html, script.js, db.mdf, db.ldf, db.ndf and data.jso etc. all in the same directory somehow ?

Thank you for the feedback and advice, much appreciated, please keep it coming.
 
This is one of those "you're trying to use a hammer to open up everything" scenarios.

Unfortunately you'd need to have some kind of server-side happening (remember "ajax" can be used server to server as well)
 
Just an update:

I have stumbled upon the FireFox addon: CORS Everywhere and works great!, Problem is I need to use IE only, so still looking for a CORS workaround for that.

Unfortunately https://crossorigin.me/ did not work for me with the reason: (CORS preflight channel did not succeed).

I have emailed the Java Dev responsible and waiting for his reply on any other possible solutions.
 
Top
Sign up to the MyBroadband newsletter
X