我正在使用角度6,并尝试发出http发布请求以登录用户
我通过以下方式为应用程序提供服务:ng serve --aot
在请求中,我有一个拦截器,它添加了一个jwt令牌:
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor() {
}
/**
* Add JWT to each requests and complete base Url
*
* @param {HttpRequest<any>} request
* @param {HttpHandler} next
* @returns {Observable<HttpEvent<any>>}
*/
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const clonedRequest = request.clone({
setHeaders: {
'Content-Type': 'application/json; charset=utf-8',
Accept: 'application/json',
Authorization: `Bearer ${AuthService.getToken()}`,
url: this.completeUrl(request.url)
}
});
return next.handle(clonedRequest);
}
/**
* Complete base url to get full endpoints
*
* @param {string} url
* @returns {string}
*/
private completeUrl(url: string) {
if (url.indexOf('http://') >= 0 || url.indexOf('https://') >= 0) {
return url;
} else {
return environment.BASE_URL + url;
}
}
}
登录功能:
public login({login, password}: SecurityPayload): Observable<SecurityToken> {
return this.http.post<SecurityToken>(
'authenticate',
{
user: login,
secret: password
},
{}
).pipe(
map((token) => {
console.log('logged in');
if (token) {
this.setToken(token);
}
return token;
}),
tap(
// Navigate to main screen through the auth.guard
_ => this.router.navigate(['/'])
)
);
}
我在return environment.BASE_URL + url;
登录了完整的URL,它是
http://localhost/authenticate
是个好人
但是在浏览器中,我得到一个带有以下URL的404:http://localhost:4200/authenticate
有什么想法吗?
答案 0 :(得分:1)
不应在headers
参数中指定url,而应直接将其作为传递给clone
方法的对象的属性
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const clonedRequest = request.clone({
setHeaders: {
'Content-Type': 'application/json; charset=utf-8',
Accept: 'application/json',
Authorization: `Bearer ${AuthService.getToken()}`,
//Do not add url here
},
url: this.completeUrl(request.url)
});
return next.handle(clonedRequest);
}
答案 1 :(得分:0)
如果您不传递任何内容,它将使用当前网址。同样在您的completeUrl方法中,您正在检查某些条件,这些条件可能会返回url端口:4200
我怀疑
if (url.indexOf('http://') >= 0 || url.indexOf('https://') >= 0) {
如果仅执行ng serve
(而不是--aot),则可以逐步调试它们。您可以在typescript类中设置断点,并查看错误所在。