代码之家  ›  专栏  ›  技术社区  ›  ParthPatel

无法从localhost执行跨域REST API调用[重复]

  •  1
  • ParthPatel  · 技术社区  · 7 年前

    我正在尝试使用JIRA在REACT中提供的RESTAPI进行登录。 但我犯了这样的错误

    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调用的帮助。

    1 回复  |  直到 7 年前
        1
  •  1
  •   brk    7 年前

    按设置尝试 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 这意味着找不到,因为它没有发送用户名&暗语