1

Hi I am trying to use ONLY JavaScript and HTML to GET the JSON object from an URL. I am using the following code:

<html>
<head>
    <title>Json</title>
    <script src="jquery-3.2.1.min.js"></script>
</head>
    <body>
        <button onclick="myFunction()">Start</button>

        <script>
        function myFunction() {
            jQuery.ajax( {
                url: 'https://iotmmss0018275632trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/app.svc/T_IOT_59824470F0BD12350F22?$format=json',
                type: 'GET',
                crossDomain: true,
                dataType: 'json',
                success: function( response ) {
                    console.log(response);
                }, 
                error : function(error) {
                    console.log(error);
                },  
            });
        }
        </script>

    </body>

As expected I am getting

Failed to load "URL": No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 401.

I cant configure the Server and I dont know if it supports CORS (Im new). I tried a JSONP request and got as response status code 200 and the JSON, but with the error:

Uncaught SyntaxError: Unexpected token :

So what can I do?

Aleksandar K.
  • 13
  • 1
  • 6
  • Does the api have docs? Does it say it supports jsonp? – Chris Phillips Oct 11 '17 at 06:47
  • I can get the data in two different formats: xml and json. I tried jsonp request, because its the only method without getting the error: Failed to load "URL": No 'Access-Control-Allow-Origin' header ... – Aleksandar K. Oct 11 '17 at 07:47
  • jasonp only works if the API supports jsonp, its not the same as vanilla json. If you don't have control over the server (to add cors support), you could create your own server to proxy the call to the api for you... – Chris Phillips Oct 11 '17 at 07:56

1 Answers1

2

You should try to go through this answer here. It has covered this topic in details.

P.S.: Should've commented this but couldn't as I don't have the required reputation points.

Shashank Goyal
  • 153
  • 1
  • 5