我只是想与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网站。我可以从头到尾解决这个问题吗?
最佳答案
您应该在 manifest.json 中定义服务器域的权限。
"permissions": ["https://MYWEBSITE.com/*"]
还要确保设置正确的协议(protocol),无论是http还是https。