我正在尝试使用新发布的HttpClient
在Angular 4
中实现基本授权。
我正试图连接到运行在Tomcat
上公开了REST
API的Spring
应用程序。
我在LoginComponent
中有以下代码:
onSubmit(user){
console.log(user);
const body = JSON.stringify({username: user.userName, password: user.password});
let headers = new HttpHeaders();
headers.append("Authorization", "Basic " + btoa("username:password"));
headers.append("Content-Type", "application/x-www-form-urlencoded");
this.http.post('my url here',body, {headers: headers}).subscribe(response => {
console.log(response);
}, err => {
console.log("User authentication failed!");
});
}
然而,该请求根本没有添加Authorization
头。
这是来自Chrome
工具中的Network
选项卡:
我做错了什么?如何使它工作?
更新1:仍然无法正常工作:
我将我的两行更改如下:
headers = headers.append("Authorization", "Basic " + btoa("username:password"));
headers = headers.append("Content-Type", "application/x-www-form-urlencoded");
我得到了预期的请求头。这是来自Chrome
:
然而,POST调用仍然失败。
在服务器端,我的代码是:
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String authCredentials = request.getHeader("Authorization");
if(authCredentials == null) {
logger.info("Request with no basic auth credentials {}", request.getRequestURL());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// do my stuff
}
调用从未到达do my stuff
,“authCredentials”为null
。
这是来自chrome
的:
该怎么办?
http
-@angular/common/http
还是@angular/http
? - Ajit Soman