2016-09-22 33 views
0

允許我使用angularjs2在前端& 的Java春作爲後端的REST API &得到錯誤。請求頭場沒有被接入控制允許的報頭預檢響應

XMLHttpRequest cannot load 'Some url'. Request header field appkey is not allowed by Access-Control-Allow-Headers in preflight response. 

這是我的角碼。

private logInUrl = 'Some url'; // URL to JSON file 


    authenticateUserCredentials(logIn: LogIn): Observable<ResponseClass> { 

    let body = JSON.stringify(logIn); 
    let headers = new Headers(); 
    headers.append('Content-type', 'application/json'); 
    headers.append('appKey', 'superadmin'); 

    let options = new RequestOptions({ headers: headers }); 

    return this.http.post(this.logInUrl, body, options) 
        .map(this.extractData) 
        .catch(this.handleError); 
    } 

和我們使用過濾器的服務器端代碼。

public final class CorsFilter extends OncePerRequestFilter{ 
    @Override 
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 
      throws ServletException, IOException { 
      // CORS "pre-flight" request 
      response.addHeader("Access-Control-Allow-Origin", "*"); 
      response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); 
      // response.addHeader("Access-Control-Allow-Headers", "Content-type,X-Requested-With,Origin,accept"); 
      response.addHeader("x-access_token","Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); 
      response.addHeader("Access-Control-Max-Age", "1800");//30 min 

     filterChain.doFilter(request, response); 
    } 
} 

郵遞員應用程序的REST API工作正常與兩個頭的AppKey &內容類型

這是爲了實現對AppKey頁眉或請提出任何其他方式發送的正確方法自定義標題或預定義標題中的自定義數據。

+0

預檢請求是一個「選項」,請確保在請求中允許「選項」。 – Supamiu

+2

您在代碼中註釋掉的行是設置Access-Control-Allow-Headers的正確方法,但錯誤是表示它期望允許請求標頭。嘗試將其添加到列表中 –

回答

0

Angular2是較低層的標頭!

所以Content-Type將是content-type,請檢查您的後端將允許它! :)

也看到這個問題:Cross orgin error in google chrome for the api call

有我解釋如何測試Angular2-後的方法來驗證角部分工作正常。

+0

感謝您的答案,但交叉問題已通過向上面的代碼中顯示的java spring添加過濾器來解決。如果我刪除自定義標頭** appKey **,則發佈請求可以正常工作。 –

相關問題