0

As titled,

I tried to access the Jenkins API (Jenkins latest version, which is 2.204.1) using the Jenkins library. I tried to make a call to retrieve the build log using the following code in React

import Jenkins from 'jenkins'

// ngrok is used to expose Jenkins's URL to the internet, so that Github webhooks can connect properly to the Jenkins.
const jenkinsConfig = {
    baseUrl : 'http://username:password@URLToMyJenkins.ngrok.io', 
    crumbIssuer: true
};
const _jenkins = Jenkins(jenkinsConfig);

useEffect(() => {
    const getBuildLog = () => {
        runner.build.get({
                name: 'jobname',
                number: 1
            }, (err, data) => {
            if (err){
                console.log('Its on err!!! ::: ', err);
            } 

            console.log('Can i see what is the data ::: ', data);
        });
    }
}, []);

When i run the above code, it throws me the CORS error, but on the ngrok console, i can see that the API was successfully called (status 200)

OPTIONS /job/GHTest2/1/api/json                                           200 OK

On the web console

Access to fetch at 'http://URLToMyJenkins.ngrok.io/job/GHTest2/1/api/json' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I installed Jenkins CORS-Filter-Plugin, and put the following configs onto it

Access-Control-Allow-Origins - http://localhost:3000, http://URLToMyJenkins.ngrok.io
Access-Control-Allow-Methods - GET, PUT, OPTIONS
Access-Control-Allow-Headers - origin, Content-Type, X-Requested-With
Access-Control-Expose-Headers - origin, *
Access-Control-Max-Age - 999

And even disable the security and CSRF protection in Jenkins, still didnt work and keep hitting the CORS error.

Did i do anything wrong here, or Jenkins API simply is not accessible from the frontend side using Javascript?

Fred A
  • 1,602
  • 1
  • 24
  • 41
  • 1
    Check the response your browser received, does it response with the correct `Access-Control-Allow-Origin` header? – Zmen Hu Jan 17 '20 at 04:02
  • @ZmenHu on network tab on the inspector, the response tab is empty. On the headers tab, it shows that the request was successfully (200). – Fred A Jan 17 '20 at 04:08
  • So does the headers tab contains a header called `Access-Control-Allow-Origin` ? The header is required to pass the CORS mechanism. You can check it here [link](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) – Zmen Hu Jan 17 '20 at 06:24

1 Answers1

1

Managed to solve this by setting the following on Jenkins's CORS configuration

Access-Control-Allow-Headers - Authorization

With that, all the codes above finally can work as expected.

Fred A
  • 1,602
  • 1
  • 24
  • 41