[英]Angular 4 - No 'Access-Control-Allow-Origin' header is present on the requested resource
[英]No 'Access-Control-Allow-Origin' header is present on the requested resource - Angular 5
我正在嘗試通過具有跨域相關標頭集的我的角度服務訪問Web服務。 但是,我仍然無法訪問Web服務。 瀏覽器一直在說,
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.
我可以在瀏覽器(chrome)和郵遞員中訪問相同的URL,但在角度應用程序中不能訪問。
private headers = new HttpHeaders()
.set('Access-Control-Allow-Origin', '*')
.set('Content-Type', 'application/json;charset=UTF-8')
.set('Access-Control-Allow-Headers', '*')
.set('Access-Control-Allow-Methods', 'GET, OPTIONS');
public getData(): Promise<Object> {
return this._http.get(this._url, {headers: this.headers})
.toPromise()
.then(response => {
return response;
}
)
.catch(testService.handleError);
}
有什么我想念的嗎...
因此,有兩種方法
如果您有權編輯Web服務。
您需要允許跨源資源共享。 如果您使用的是Node.js,這是添加代碼的示例
// ~ Cross origin resource sharing ~ // var cors = require('cors'); // ~ Initialize the app ~ // var app = express(); // ~ Enbling CORS ~ // app.use(cors());
您可以添加瀏覽器擴展程序,以便在瀏覽器上運行時修復角度應用程序的CORS錯誤。
這是適用於Chrome瀏覽器的https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=zh-CN
這是針對Mozilla https://addons.mozilla.org/zh-CN/firefox/addon/cors-everywhere/
您可以在https://enable-cors.org/上了解更多信息。
希望對您有所幫助。 如果有任何錯誤,請通過評論告知我。
有多種方法可以解決此問題,但是首先,您需要確定客戶端正在發送的額外請求標頭參數(如果有)。
現在可以通過使用瀏覽器的任何開發人員控制台來發現它。 另一個指針是檢查響應/錯誤是否有options
調用。
一旦確定,您將需要從服務器啟用適當的響應參數,在這種情況下,似乎選項調用未在響應中設置Access-Control-Allow-Origin
。
讓我知道這是否有助於您診斷問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.