【问题标题】:TeamCity Rest API call with CORS disabled - axios get request禁用 CORS 的 TeamCity Rest API 调用 - axios 获取请求
【发布时间】:2018-01-09 18:19:50
【问题描述】:

我正在尝试使用 axios get 请求将数据从我们的 TeamCity 服务器返回到我的 React Web 应用程序。不幸的是,我无法在服务器上启用 CORS,并且总是以 401:未授权或“预检响应无效(重定向)”错误结束。

我已尝试在标题中传递用户名和密码:

componentDidMount() {
var config = {
    "headers": {
    "username": "username",
    "password": "password"    
  }
}
// Make axios  http request to TeamCity server with authentication headers
axios.get('http://teamcity/app/rest', config)
 .then(res => res.json())
  .then(res => {
    // Transform the raw data by extracting the nested posts
    const projects = res.data.projects;

    // Update state to trigger a re-render.
    // Clear any errors, and turn off the loading indicator.
    this.setState({
      projects,
      loading: false,
      error: null
    });
  })
  .catch(err => {
    // Something went wrong. Save the error in state and re-render.
    this.setState({
      loading: false,
      error: err
    });
  });
 }

我已尝试按照此帖子在 url 中传递用户名和密码: How to pass username and password in TeamCity REST API

http://user:pass@server/app/rest/

我还尝试通过工作邮递员请求传递基本身份验证标头。

请求总是返回'XMLHttpRequest 无法加载http://teamcity/app/rest。预检响应无效(重定向)'

我与 TeamCity 服务器在同一个网络上。如果不启用 CORS,这可能吗?

【问题讨论】:

  • 这似乎是一个身份验证问题。您没有按预期传递用户/通行证。

标签: rest reactjs cors teamcity axios


【解决方案1】:

您必须启用 CORS。否则(即使 TeamCity 响应了一些数据)也无法访问浏览器中的响应。

一旦您在rest.cors.origins internal property 中提供了正确的来源,例如

rest.cors.origins=http://myinternalwebpage.org.com:8080,https://myinternalwebpage.org.com

您还应该通过添加以下内部属性来启用预检 OPTIONS 请求支持:

rest.cors.optionsRequest.allowUnauthorized=true

然后重启服务器。

The docs 也建议使用/app/rest/latest,而不是/app/rest,并避免使用httpAuth 前缀。

之后一切都应该正常工作,例如

fetch('http://teamcity:8111/bs/app/rest/latest/builds?count=1', 
{
  headers: {
    'Authorization': 'Basic '+btoa('user:pass'),
    'Accept': 'application/json'
  }
})
.then(r => r.json())
.then(r => console.log(r))

【讨论】:

  • 这不仅仅是使用/app/rest/latest 的建议:TeamCity 需要对浏览器不发送的OPTIONS /httpAuth/app/rest URL 进行身份验证,因此 CORS 请求将失败。这阻碍了我做POST 的能力,直到我偶然发现了这个答案。尽管我在文档中看到了这一点,但我没有仔细检查它,因为 GET 请求正在工作,所以我认为这不是与 URL 相关的问题。
猜你喜欢
  • 1970-01-01
  • 2020-07-08
  • 2020-05-31
  • 1970-01-01
  • 1970-01-01
  • 2015-04-03
  • 2014-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多