1

I am trying to make a function on my website to stop a running Jenkins pipeline.

I tried below,

let myHeaders = new Headers({
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json'
})
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "Basic c3RhcnNpdDpjaXNjbzEyMw==");

let requestOptions = {
  method: 'POST',
  headers: myHeaders,
  redirect: 'follow'
  mode: 'cors',
};

fetch("<my_server>/<buildNum>/stop", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

This gives me an error

Access to fetch at '<my_server>/<buildNum>/stop' 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 added the option Access-Control-Allow-Origin to the header and also set the mode to cors in the requestOptions.

Any help, please?

Dawn17
  • 7,825
  • 16
  • 57
  • 118

2 Answers2

0

The Access-Control-Allow-Origin must be present on the response not in the request. The Jenkins API must respond with this header to allow your request to proceed. Take a look on this plugin https://plugins.jenkins.io/cors-filter/.

Andrei Sena
  • 167
  • 6
0

Your server should enable CORS for /stop endpoint, so the header Access-Control-Allow-Origin will be in the response. Check this out CORS explanation

Tymur Berezhnoi
  • 706
  • 1
  • 14
  • 27