【发布时间】:2018-06-12 16:28:50
【问题描述】:
我正在尝试使用我的企业应用程序和 Angular 中提供的 REST API。我想要实现的是从我的企业应用程序中获取一些数据。为此,我必须做两件事:
1- 通过 Angular 登录到我的企业应用程序。为此,企业应用程序已经提供了一个自定义身份验证 REST API。我也吃同样的。生成了一个身份验证令牌,我将其保存在 localStorage 中。
2- 在身份验证发生后向企业应用程序发送 GET 请求以获取数据。这是我面临问题的地方。我无法在 GET 请求中传递身份验证令牌。在 Chrome 开发工具的“应用程序”选项卡下检查相同内容时,我可以在“请求标头”部分看到授权值为空。以下是相同的屏幕截图:
以下是我开发的代码:
1 - 身份验证服务 (auth.service.ts)
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import{Http} from '@angular/http'
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { URLSearchParams,Response } from '@angular/http'
@Injectable()
export class AuthenticationService {
constructor(private http: Http) { }
username:string = 'Admin';
password:string='livelink';
token:any;
login()
{
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('Username', this.username);
urlSearchParams.append('Password', this.password);
this.http.post('http://localhost/otcs/cs.exe/api/v1/auth',urlSearchParams)
.subscribe((res:Response) =>
{
// login successful if there's a jwt token in the response
if (res) {
const data = res.json();
;
this.token = data;
console.log(data);
// store username and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify({ ticket: data }));
}
});
console.log("INSIDE LOGIN this.token = "+this.token)//done for debugging, returning undefined
}
public getToken()
{
console.log("GET TOKEN VALUE "+ localStorage.getItem('ticket'))//done for debugging, returning undefined
return localStorage.getItem('ticket');
}
}
2 - 令牌拦截器 (token.interceptor.ts)
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { AuthenticationService } from './auth.service';
import { Observable } from 'rxjs';
import { Http } from '@angular/http';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthenticationService) {}
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}
3 - 应用组件 (app.component.ts)
import { Component } from '@angular/core';
import { AuthenticationService } from './auth.service';
import{Http} from '@angular/http'
import { HttpClient } from '@angular/common/http'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent
{
constructor(private authenticationService: AuthenticationService, private
http:HttpClient)
{
this.authenticationService.login();
this.ping() ;
}
public ping() {
this.http.get('http://localhost/otcs/cs.exe/api/v1/nodes/16236/output')
.subscribe(
data => console.log(data),
err => console.log(err)
);
}
}
4- 应用模块 (app.module.ts)
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from
'@angular/common/http';
import { AppComponent } from './app.component';
import { AuthenticationService } from './auth.service';
import { HttpModule } from '@angular/http';
import { TokenInterceptor } from './token.interceptor';
@NgModule({
declarations:[AppComponent],
imports: [
BrowserModule,
HttpClientModule,
HttpModule
],
providers: [AuthenticationService,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}],
bootstrap: [AppComponent]
})
export class AppModule { }
在运行上述项目时,以下是控制台中显示的输出:
我无法理解为什么我的令牌没有通过 GET 请求传递。
【问题讨论】:
-
在代码中添加一些日志语句以缩小问题范围。
-
您好亨利,最后一个屏幕截图来自显示错误的控制台窗口。问题是我的 GET 请求无法获取授权令牌。我从 POST 请求中成功生成了相同的内容,但是在尝试将其附加到 GET 请求时,我收到了未经授权的错误
标签: javascript angular angular4-httpclient