Chrome扩展程序已阻止Chrome API

时间:2015-11-03 05:31:49

标签: javascript google-chrome-extension cors

我只是想在Rails网站上与REST api交谈。 我正在使用Chrome扩展程序和javascript来制作CORSRequest。

每当我尝试发出请求时,都会收到此错误:

XMLHttpRequest cannot load https://MYWEBSITE.com/api/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://mychomreextensioncode' is therefore not allowed access. The response had HTTP status code 404.

这是我目前的代码:

function makeCorsRequestLogin() {


  var url = "https://MYWEBSITE.com/api/login";
  var xhr = new XMLHttpRequest();
  xhr.open('POST', url, true);
  xhr.setRequestHeader('Content-type', 'application/json');
  xhr.onload = function() {
    var text = xhr.responseText;
    var title = text; //getTitle(text);
    alert('Response from CORS request to ' + url + ': ' + title);
  };

  if (!xhr) {
    alert('CORS not supported');
    return;
  }
  xhr.onerror = function() {
    alert('Woops, there\'s an error making the request.');
  };
  var password = document.getElementById("password").value;
  var user_name = document.getElementById("username").value;
  xhr.send(JSON.stringify({"user_name":user_name, "password":password}));
}

在其他地方,过去人们都说这个代码解决了它。但是,我不知道这可能会发生什么。

# This is used to allow the cross origin POST requests made by confroom kiosk app.
  def set_access_control_headers
    headers['Access-Control-Allow-Origin'] = "*"
    headers['Access-Control-Request-Method'] = %w{GET POST OPTIONS}.join(",")
  end

我只在Chrome扩展程序上使用JS和HTML。我无法访问ruby网站。我能从我的最终解决这个问题吗?

1 个答案:

答案 0 :(得分:6)

您应该在 manifest.json 中为您的服务器域定义权限。

"permissions": ["https://MYWEBSITE.com/*"]

还要确保设置正确的协议,无论是http还是https。