0

I've trying to communicate with JDoodle API Server using JavaScript (JQuery), but everytime it says, CORS error. But when I did the same using Java Servlets, it was perfectly working. I used axios, but it also says 'Network Error'. My function looks like this:

function x()
        {
            var dataJ = {
                clientId: ''XXXXXXXXX,
                clientSecret:'XXXXXXXXXX',
                language:'PHP',
                script:'',
                versionIndex: '0'
            };
            $.ajax({
                type:'POST',
                url:'https://api.jdoodle.com/v1/execute/',
                data: dataJ,
                success: function(e)
                {
                    console.log(e);
                },
                error: function(e)
                {
                    console.log(e.statusText);
                }
            });
        }

2 Answers2

0

its a security policy that dont let to other client use a site functionality:

see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

only page of that site can send message to site or that site active allow-access-allow-origin on own site

Mahdi Aslami Khavari
  • 1,755
  • 15
  • 23
0

CORS is controlled by backend API and in your case, you don't have control over it which is https://api.jdoodle.com/v1/execute/.

Browser prevents your code from accessing the response because the browser can't see Access-Control-Allow-Origin in response.

Things can still get working by making the request through a Proxy can where a proxy sends appropriate CORS header on behalf of your request.

const proxy = "https://cors-anywhere.herokuapp.com/";
const url = "https://api.jdoodle.com/v1/execute/"; 
fetch(proxy + url)
  .then(response => response.text())
  .then(contents => console.log(contents))
  .catch(() => console.log("CORS Error" + url ))

For your case

const proxy = "https://cors-anywhere.herokuapp.com/";
const url = "https://api.jdoodle.com/v1/execute/";

function x() {
  var dataJ = {
    clientId: "XXXXX",
    clientSecret: "XXXXXXXXXX",
    language: "PHP",
    script: "",
    versionIndex: "0"
  };
  $.ajax({
    type: "POST",
    url: proxy + url,
    data: dataJ,
    success: function(e) {
      console.log(e);
    },
    error: function(e) {
      console.log(e.statusText);
    }
  });
}

Making a request through a proxy will work this way

  1. CORS proxy will forward your request to https://api.jdoodle.com/v1/execute/
  2. The return response from https://api.jdoodle.com/v1/execute/ with Access-Control-Allow-Origin headers.
  3. Now your browser can see Access-Control-Allow-Origin headers present in the response header.

For more detail explanation you can check out this

https://stackoverflow.com/a/43881141/2850383

Object object
  • 872
  • 6
  • 18