網站搜尋

neo4j - 請求選項 "withCredentials" - Angular2


我在使用 request 連接 Neo4j 到 Angular2 元件時遇到 CORS 問題:

Response to preflight request doesn't pass access control check. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:8080' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute

我該如何在使用 request(Typescript)時設置 withCredentials: false?我假設這可以解決問題。但 request 的 ts 文件中在它的 CoreOptions 對象裡沒有列出 withCredentials。Neo4j-Typescript 套件在其 Typescript 定義中也沒有包含這個屬性。

答案#1

你可以透過擴展 BrowserXhr 類別來做到這一點:

@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
  constructor() {}
  build(): any {
    let xhr = super.build();
    xhr.withCredentials = false;
    return <any>(xhr);
  }
}

並使用擴展版本覆蓋 BrowserXhr 提供者:

bootstrap(AppComponent, [
  HTTP_PROVIDERS,
  provide(BrowserXhr, { useClass: CustomBrowserXhr })
]);

答案#2

我在我的 Angular2 應用程式中也遇到同樣的問題。問題是,在客戶端發出的每個請求之前,會向伺服器發送一個 預檢請求。

這種類型的請求具有一個 OPTIONS 類型,伺服器的職責是返回一個狀態為 200 並設置了接受該客戶端請求的標頭的 預檢響應。

這是我的解決方案(使用 express):

// Domain you wish to allow
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');

// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'YOUR-CUSTOM-HEADERS-HERE');

// Set to true if you need the website to include cookies in  requests
res.setHeader('Access-Control-Allow-Credentials', true);

// Check if Preflight Request
if (req.method === 'OPTIONS') {
    res.status(200);
    res.end();
}
else {
    // Pass to next layer of middleware
    next();
}

如你所見,我設置了標頭,然後如果請求類型是OPTIONS,就進行抓取。在這種情況下,我會回傳狀態200並結束回應。

這樣一來,客戶端將被授權,您也將能夠在所有請求中設置自訂標頭,而不必再擔心 CORS 問題。