0
將跨域XMLHttpRequest發送給Restivus API時出現問題。 這裏我的客戶端腳本代碼:XMLHttpRequest Restivus API
var xhrurl = 'http://example.com:3000/api/test';
var xhr = createCORSRequest('POST', xhrurl);
xhr.withCredentials = true;
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("X-User-Id",object.apiUser);
xhr.setRequestHeader("X-Auth-Token",object.apiKey);
xhr.send();
這裏的功能createCORSRequest
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
當它發送到我的API的響應401授權。 apiKey和UserId是正確的,因爲我用郵差測試了它們,所以不應該有問題。
我的後端是流星使用Restivus API。
我已經在服務器端腳本的頂部添加了這些行,以確保一切都被接受。
WebApp.connectHandlers.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, X-User-Id, X-Auth-Token");
res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
res.setHeader("Access-Control-MaxAge", "3628800");
res.setHeader("Access-Control-Allow-Credentials", true);
return next();
});
而且我已經定義了路由的restivus調用類似如下:
Restivus.addRoute('test/', {authRequired: true}, {
post: {
action: function() {
var test=Projects.find({userId:this.userId, _id: this.bodyParams.project}).count();
if(this.bodyParams.msg==""||this.bodyParams.msg==undefined||this.bodyParams.project==""||this.bodyParams.project==undefined||test!=1){
return 'Something went wrong'
}
var test = Test.insert({msg: this.bodyParams.msg, date: new Date(), userId : this.userId, fixed: false, project: this.bodyParams.project});
if (test) {
return {statusCode:200,headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
},body: "success"};
}
return {
statusCode: 400,
body: {status: "fail", message: "Test"}
};
}
},
options: {
action: function() {
return {statusCode:200,headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Method': '*',
'Access-Control-Allow-Headers': 'Content-Type, X-User-Id, X-Auth-Token'
}};
}
}
});
我已經加入的選項和POST方法允許預檢和實際的崗位,然後,但我總是得到授權作爲迴應,雖然我包含登錄憑證,如在指定的Restivus文檔中(他們在Postman中工作)。 那麼問題在哪裏呢?
我很高興你能弄清楚這一點。在Restivus v0.8.0的下一次更新中,我做到了這樣,OPTIONS端點不再受路由上的身份驗證和角色要求的影響。這些選項現在必須在OPTIONS端點上顯式配置,以避免這種意外的行爲。如果一切按照計劃進行(約什麼時候?),v0.8.0應該在大約兩週內出來。 https://github.com/kahmali/meteor-restivus/commit/a1630865c861a1448c7bdb6c71fca0b889d04209#diff-5d6d4c4facf5b6f28ea5dc0f8a86ce9eR101 – kahmali