【发布时间】:2018-02-04 06:50:11
【问题描述】:
我正在尝试使用新发布的HttpClient 在Angular 4 中实现基本授权。
我正在尝试使用暴露的 REST API 连接到在 Tomcat 上运行的 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 call 仍然失败。
在服务器端,我的代码是:
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 -
@AjitSoman: @angular/common/http...
-
Ben 的回答对您有用吗?您是否在控制台中收到有关 cors 的任何错误?
-
我在 google chrome 中安装了一个 CORS 插件来解决 CORS 问题,以便在开发模式下调试和运行。
标签: java spring angular google-chrome tomcat