我正在开发一个Chrome应用程序,将通过RESTful API与服务器通信。
在未将服务器URL添加到manifest.json的权限中时,我可以看到Chrome发送所有带有起始头(chrome-extension://cpndc...)的请求,如果这些请求中有非标准头,则还会发送预检OPTIONS请求 - 这都是预期的行为。
添加了域到权限后,预检OPTIONS就不再发送。 GET调用中没有出现起源头,但在POST、PATCH、MERGE调用中仍然存在。
这会导致问题,因为我将使用的服务器上的CORS实现假定带有起源头的请求是CORS请求,并响应403错误,因为它不喜欢该起源 - 带有chrome-extension的起源不在接受的起源列表中。
根据CORS规范,期望的是起源头只在跨域请求中添加https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Origin,但由于服务器域已添加到权限中,我希望不仅GET而且其他请求也没有它。
问题是:这是Chrome Apps CORS实现中的错误吗?
在使用Chrome应用程序时,我的发现总结如下:
如果在清单文件中未添加终端点URL的权限(将启用CORS): - Chrome App在所有类型的请求中发送起源头 - Chrome App为具有非标准头的所有请求发送OPTIONS预检
如果在清单文件中添加了终端点URL的权限(关闭对该域的请求的安全性): - Chrome Apps不再发送OPTIONS预检(预期) - Chrome App仅在非GET请求中发送起源头(根本不应该发送起源)
权限文件示例:
"permissions": [
"http://api.randomuser.me/*"
示例应用程序代码:
window.onload = function() {
function get(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.randomuser.me/?seed=bigFish", true);
xhr.setRequestHeader('Authn', 'abcdefghijklmnopqrstuvxyz');
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
post();
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
}
function post() {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://api.randomuser.me/', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Authn', 'abcdefghijklmnopqrstuvxyz');
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send('user=person&pwd=password&organization=place&requiredkey=key');
}
document.getElementById('mybutton').addEventListener('click', function() {
get();
});
};
没有Origin头的GET请求:
带有Origin头的POST请求: