【问题标题】:Can not do cross domain REST API Call from localhost [duplicate]无法从本地主机进行跨域 REST API 调用 [重复]
【发布时间】:2018-08-21 05:35:59
【问题描述】:

我正在尝试使用 JIRA 在 REACT 中提供的 REST API 进行登录。 但我收到了类似

的错误
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:8085' is therefore not allowed access. The response had HTTP status code 403. 
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

下面是我正在测试登录的代码。

fetch("https://jira.company.com/rest/auth/latest/session",{
  method:'POST',
  headers: {
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin" : "*"
  },
  body: 
    JSON.stringify({
    username:"username",
    password : "password"})
  }).then(result => console.log(result));

我也尝试过使用以下参数,但结果相同。

'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',

我还查看了JIRA API 的文档,但找不到任何用于跨域请求访问的内容。 寻求帮助以跨域进行 API 调用。

【问题讨论】:

  • REST API 不打算从浏览器调用(也就是没有“Access-Control-Allow-Origin”标头)。您可以从服务器获取它,例如卷曲。顺便说一句,用户名/密码通常在标头中发送btoa
  • 感谢 Ron,因为这些 API 受保护,无法通过浏览器访问。有没有办法从浏览器调用受保护的 API?

标签: javascript reactjs jira-rest-api


【解决方案1】:

尝试设置mode: 'cors'

fetch("https://jira.company.com/rest/auth/latest/session", {
  method: 'POST',
  headers: {
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*"
  },
  mode: 'cors',
  body: JSON.stringify({
    username: "username",
    password: "password"
  })
}).then(function(resp) {
  return resp.json();

}).then(function(data) {
  console.log(data)
});

注意:在演示中你可能会看到404,这意味着找不到,因为它没有发送用户名和密码

【讨论】:

  • 我已经尝试过使用 mode:'cors' 但它并没有解决我的问题。我尝试使用 POSTMAN 进行相同的 API 调用,并且它工作正常,无需在请求中提供模式。
  • 你还在看 403 吗?
  • 是的,仍然是 403。
  • 当我在 chrome 中检查请求时出现“XSRF 检查失败”
  • 可能与 cors 不同
猜你喜欢
  • 2016-08-31
  • 2011-04-20
  • 1970-01-01
  • 2011-04-10
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2013-04-26
相关资源
最近更新 更多