簡體   English   中英

如果響應中缺少CORS標頭,則角度$ http不返回.error()變量

[英]angular $http not returning .error() variables if CORS headers are missing from the response

我正在通過websockets執行$ http.get,而.error不會填充任何參數。 我使用的是Angle 1.3.5,OSX上的最新版Chrome和本地主機的別名為mywebsite.com。

$http({method: 'GET', 'ws://mywebsite.com/resource'})
.success(function(response){ ... })
.error(function(err, status){
   console.log(err); <<< here err and status are null respectively 0 even the XHR Response logs 401 in console.
});

有任何線索為什么這樣做? 不管是什么錯誤代碼,它都不會傳遞給錯誤回調。 對於2xx響應,我確實獲得了數據,一切都很好。

為了澄清起見,.error回調被正常調用,但是沒有填充err和status。

好吧,好吧,我發現了正在發生的事情。 一堆東​​西。

首先,我正在使用KOA,而以上介紹的角度都將KOA作為REST API。 我還使用koa-jwt對用戶進行身份驗證並生成令牌。

現在,該api在子域上運行,甚至我都通過koa-cors設置了CORS以允許*訪問。

問題是當令牌過期時,koa-jwt會執行this.throw(401)。 KOA的處理方式是立即終止后續中間件並退出並顯示該錯誤。 那就是,無論我將中間件放在哪里(不允許在koa-jwt之前或之后),都​​不允許設置koa-cors標頭。

因此,最佳的解決方法是將我的頂級產量包裝在try catch中,並避免允許koa-jwt ctx.throw傳播。

在Angular方面,瀏覽器拒絕將401傳遞給.error,抱怨它找不到合適的CORS來允許它處理和移交響應:)。

app.use(cors({origin:"*", methods:'GET,HEAD,PUT,POST,DELETE,PATCH'}));  //allow all origins to the API. 
app.use ( function *(next){
    try {
      yield next;
    } catch (err) {
      this.status = err.status || 500;
      this.body = err.message;
      this.app.emit('error', err, this);
    }
});

... more middleware
// middleware below this line is only reached if jwt token is valid
app.use(jwt({secret: config.app.secret}));

允許來自koa-jwt的this.trow(401)將破壞您的一天。

我認為您只是打錯字,只是這樣寫:

$http({method: 'GET', 'ws://mywebsite.com/resource', headers: headers})
.success(function(response){ ... })
.error(function(err, status){
   console.log(err);
});

但是,作為最佳實踐,我會這樣做

var request = {
   method: 'GET',
   url: 'ws://mywebsite.com/resource',
   headers: {//insert here header you want, put Origin header only for example purposes
      Origin: 'ws://mywebsite.com/resource'
   }
}

$http(request)
.success(function(response){ ... })
.error(function(err, status){
   console.log(err);
});

如果輸入錯誤不是錯誤(您可以復制代碼),只需看一下從未調用過的AngularJS $ http錯誤函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM