允許我使用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頁眉或請提出任何其他方式發送的正確方法自定義標題或預定義標題中的自定義數據。
預檢請求是一個「選項」,請確保在請求中允許「選項」。 – Supamiu
您在代碼中註釋掉的行是設置Access-Control-Allow-Headers的正確方法,但錯誤是表示它期望允許請求標頭。嘗試將其添加到列表中 –