首页 > 解决方案 > 在 JavaScript 上使用 Jenkins REST /stop 给了我 CORS

问题描述

我正在尝试在我的网站上创建一个功能来停止正在运行的 Jenkins 管道。

我在下面尝试过,

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));

这给了我一个错误

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.

我将选项添加Access-Control-Allow-Origin到标题modecors,并将requestOptions.

请问有什么帮助吗?

标签: javascriptjenkinscors

解决方案


您的服务器应该为/stop端点启用CORS ,因此标头Access-Control-Allow-Origin将在响应中。看看这个CORS 解释


推荐阅读