問題描述
XMLHttpRequest 響應:預檢請求未通過訪問控制檢查: (XMLHttpRequest response: preflight request does not pass the access control check:)
我正在嘗試使用以下 http post 請求訂閱 firebase 雲消息傳遞主題:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://iid.googleapis.com/iid/v1/etLaB36oW1w...nyO_Zc26ZPOFTeNuf58‑l6uSoJ9Xs1JRYKfqxsmKkdrR‑oX4tQsuS_z5C0/rel/topics/Byfjordskole");
xhr.setRequestHeader("authorization", "key=AAAABlxTfxY:APA91bGE3sa09zq...dZSIVJul3N‑y1hMJqAoKngwjC_El3rEuH4_‑S2gOxKcdAF67HHhGK7pAWJrhyt8JthJGm_QN6JdXTBow62nYodgFvLncfSniwtBinBgIPLaKpT");
xhr.setRequestHeader("content‑type", "application/json");
xhr.setRequestHeader("cache‑control", "no‑cache");
xhr.setRequestHeader("postman‑token", "a3ce72a5‑f8ba‑99e4‑59d6‑fe3295b84f6e");
xhr.send(data);
這在我使用 Postman 時有效,但當我嘗試使用相同時收到以下錯誤消息我的 javascript 應用程序上的代碼:
XMLHttpRequest cannot load https://iid.googleapis.com/iid/v1/eOEiRqvhD4s:APA91bFFb‑uP‑Xhf2iD‑ALUI_X4M7…gA_YgQgmuib7cCL7UuSdlhUUWmsqwRnkcO2kpAIV_H‑_xBPlPd/rel/topics/Eiganesskole.
Response to preflight request doesn't pass access control check:
No 'Access‑Control‑Allow‑Origin' header is present on the requested resource.
Origin 'https://sk......e.top' is therefore not allowed access.
firebase 雲消息傳遞是否會阻止我發出此類請求,或者是否有解決此問題的方法?任何幫助將不勝感激。
參考解法
方法 1:
This Stack Overflow answer solved my problem: https://stackoverflow.com/a/2067584/6177181
The problem was browser security related: and this kept me from making cross domain requests. The Solution was to wrap my code in script tags to avoid this restriction. So instead of doing this request from another javascript file, I simply added the request code in the index.html file like this:
<script>
function subscribe(currentToken){
"use strict"
let stored_topics = localStorage.getItem("topicsList");
let topics = JSON.parse(stored_topics);
for (let i = 0; i < topics.length; i++){
let data = null;
let xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
let body = {};
let url = "https://iid.googleapis.com/iid/v1/"+currentToken+"/rel/topics/"+topics[i];
xhr.open("POST", url);
xhr.setRequestHeader("authorization", "key=AAAABlxTfxY:....QAVfBJI8J0RdZSIVJul3N‑y1hMJqAoKngwjC_El3rEuH4_‑S2gOxKcdAF67HHhGK....2nYodgFvLncfSniwtBinBgIPLaKpT");
xhr.setRequestHeader("content‑type", "application/json");
xhr.send(data);
}
}
</script>
(The currentToken is requested from the firebase cloud messaging API in the same file(index.html)). Follow the instructions on this link :https://firebase.google.com/docs/cloud‑messaging/js/receive for information about Firebase cloud messaging.
(by Jan Bildus、Jan Bildus)