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?
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.