Javascript 来自rails API的Chrome扩展被阻止

Javascript 来自rails API的Chrome扩展被阻止,javascript,google-chrome-extension,cors,Javascript,Google Chrome Extension,Cors,我只是想在Rails站点上使用RESTAPI。 我正在使用一个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' heade

我只是想在Rails站点上使用RESTAPI。 我正在使用一个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站点的权限。我能从我的角度解决这个问题吗?

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

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

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

我在底部说,我无法访问ruby服务器。我问我是否能从我这边解决这个问题。我理解你的评论,这个问题的答案是否定的。对吗@JaromandaXsorry,我错过了“ruby”的评论。。。但是我也忘了你说的是google chrome扩展-因此,你可以在不访问服务器的情况下做你需要做的事情-关键是你的manifest.json文件(对不起,我找不到网页)谢谢你,我刚刚将服务器的URL添加到了manifest的权限中,它工作起来很有魅力@Jaromandaxindate,不访问服务器,这是唯一的解决方案。