Vic*_*cky 21 java spring tomcat google-chrome angular
我正在尝试Angular 4使用新发布的实现基本授权HttpClient.
我正在尝试连接到使用公开API Spring运行的应用程序.TomcatREST
我的代码中包含以下代码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!");
});
}
Run Code Online (Sandbox Code Playgroud)
但是,请求根本不添加Authorization标头.
这来自Chrome工具Network选项卡:
我究竟做错了什么?我怎样才能做到这一点?
更新1:它仍然无法正常工作:
我改变了我的两行,如下所示:
headers = headers.append("Authorization", "Basic " + btoa("username:password"));
headers = headers.append("Content-Type", "application/x-www-form-urlencoded");
Run Code Online (Sandbox Code Playgroud)
我按预期在请求中获得标题.这来自Chrome:
但是,后调用仍然失败.
在服务器端,我的代码是:
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
}
Run Code Online (Sandbox Code Playgroud)
呼叫永远不会到达do my stuff.authCredentials是null.
这来自chrome:
如何进行?
这是有效的:
我不得不做两个步骤:
1)我必须将Angular 4行更改为我在Update 1中所做的操作,因为它HttpClient是不可变的.
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!");
});
}
Run Code Online (Sandbox Code Playgroud)
2)现在根据您的要求,您有两种选择:
a)使用此处说明的代理来解决CORS问题而不更改服务器端.
b)按照此处的说明更新服务器端,并在下面的一些答案中更改弹簧配置.
Ben*_*ley 28
HttpHeaders是不可变的,因此您需要分配函数的结果以覆盖headers每次调用的对象.
let headers = new HttpHeaders();
headers = headers.append("Authorization", "Basic " + btoa("username:password"));
headers = headers.append("Content-Type", "application/x-www-form-urlencoded");
Run Code Online (Sandbox Code Playgroud)
资料来源:Angular Docs
| 归档时间: |
|
| 查看次数: |
29460 次 |
| 最近记录: |