My code looks like this;
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
let token = localStorage.getItem('token');
let newRequest: HttpRequest<any>;
newRequest = request.clone({
headers: request.headers.set('Authorization', 'Bearer ' token),
});
console.log(newRequest)
return next.handle(newRequest);
}
And my headers that sends to backend looks like this;
key
:
"authorization"
value
:
['Bearer "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLz…eiAQgeeiwwfbJ_gzDb2mI5FPx8WOLWcJaku9cGgcrdORIP6A"']
I want to send my headers like;
key
:
"authorization"
value
:
['Bearer eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLz…eiAQgeeiwwfbJ_gzDb2mI5FPx8WOLWcJaku9cGgcrdORIP6A']
I know I need to push Bearer into token but how;
headers: request.headers.set('Authorization', 'Bearer ' token),
I want to know what is the true piece of code to do that?
CodePudding user response:
TLDR;
JSON.parse(localStorage.getItem('token'));
You get the string stored in the local Storage, the string is transformed to json and saved as a string (JSON.stringify
) to local storage. When you read the json-string out, you need to parse the json-string again to get the original string back.
CodePudding user response:
Try this way:
let token = localStorage.getItem('token');
newRequest = request.clone({
headers: request.headers.set('Authorization', `Bearer ${token}`),
});