How to pass Authorization Header Token in api call in angular
Solution 1
Try like this:
Use HttpClient
import { Injectable } from "@angular/core";
import { HttpClient,HttpHeaders } from '@angular/common/http';
@Injectable()
export class ApiService {
constructor(private http: HttpClient) {}
getTransferIp() {
let header = new HttpHeaders().set(
"Authorization",
localStorage.getItem("token")
);
return this.http.get("http://localhost:3003/transferip", {headers:header});
}
}
Solution 2
To intercept http requests in angular, you can write a service that implements HttpsInterceptor
interface from common/http
module.
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = 'token...'; // your auth token
if (authorized) { // your authorized logic
request = request.clone({
setHeaders: {
Authorization: `${token}`
}
});
}
return next.handle(request);
}
}
Don't forget providing your service in your module.ts file
{provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor},
Solution 3
You can create an interceptor to add the Authorization
header for every request.
If you want to add the header for only this specific request, temporarily, you can use something like this.
getTransferIp(){ {
const token = localStorage.getItem("token");
const header = new Headers({ 'Authorization': `Bearer ${token}` });
const options = {
headers: header,
};
return this.http.get('http://localhost:3003/transferip', options);
}
Related videos on Youtube
Aayush Gupta
Beginner in MEAN Stack. Past worked in PHP/MySQL. Aspiring to learn more.
Updated on June 04, 2022Comments
-
Aayush Gupta almost 2 years
I am using a get api call to fetch the data from json doc using http. But i have enabled authorization to only token bearer. I want to pass the value of token (which i can get through
localStorage.getItem("token");
) in my Authorization in the headers when i call the get request.API.SERVICE.TS
import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs'; import { HttpClientModule } from '@angular/common/http'; import { HttpClient, HttpRequest, HttpEventType, HttpHeaders, HttpParams, HttpEvent, HttpErrorResponse, HttpResponse } from '@angular/common/http'; import 'rxjs/add/operator/map'; @Injectable({ providedIn: 'root' }) export class ApiService { constructor(private http: Http) { } getTransferIp(){ return this.http.get('http://localhost:3003/transferip').map(res => res.json() ); } }
Currently i am allowed to fetch the data only when i turn off the auth in my node server get router... But i dont want to do that and also without using interceptor
Attatching Node Server Files below...
AUTH.JS
const jwt = require('jsonwebtoken') const User = require('../models/user') const auth = async (req, res, next) => { try { const token = req.header('Authorization').replace('Bearer ', '') const decoded = jwt.verify(token, 'mango@123') const user = await User.findOne({ _id: decoded._id, 'tokens.token': token }) if (!user) { throw new Error() } req.token = token req.user = user next() } catch (e) { res.status(401).send({ error: 'Please authenticate.' }) } } module.exports = auth
TRANSFERIP.JS (ROUTER)
const express = require('express') const TransferIp = require('../models/transferip') const auth = require('../middleware/auth') const router = new express.Router() router.post('/transferip', auth, async (req, res) => { const task = new TransferIp({ ...req.body, owner: req.user._id }) try { await task.save() res.status(201).send(task) } catch (e) { res.status(400).send(e) } }) router.get('/transferip', auth, function(req, res, next) { TransferIp.find(function (err, events) { if (err) return next(err); res.json(events); }); }); module.exports = router
SCREENSHOT OF SUCCESSFUL GET REQUEST WITH TOKEN USING POSTMAN
-
Jason White over 4 yearsYou can use an interceptor. medium.com/@ryanchenkie_40935/…
-
-
Jason White over 4 yearsin the network tab of your browser, does the request contain the Authorization header?
-
Aayush Gupta over 4 yearsyes it does. and fyi when i get the request through postman adding the token, it works
-
Adrita Sharma over 4 yearsWhy are you using map, which version of Angular are u using
-
Jason White over 4 yearsIs it a cors issue? Is there an options request before the api request that fails? In the console of the browser, is there a Cross Origin error?
-
Aayush Gupta over 4 yearsim using 8.2 btw getting this error while trying ur answer ``` Argument of type 'HttpHeaders' is not assignable to parameter of type 'RequestOptionsArgs'. Property 'headers' is private in type 'HttpHeaders' but not in type 'RequestOptionsArgs' ```
-
Adrita Sharma over 4 yearsUse httpclient, constructor(private http: HttpClient) { }
-
Adrita Sharma over 4 yearsCan you try the latest?
-
Aayush Gupta over 4 yearstried. no luck :( btw im not getting the 2nd comment error. but i am not able to fetch the data as i am getting 401:unauthorized
-
Adrita Sharma over 4 yearsWhat kind of authorization does your backend have? Btoa? Bearer? Try it using postman and show how it worked
-
Aayush Gupta over 4 yearsi have added more details in the question. please check
-
Adrita Sharma over 4 yearsIn authorization header, before the value, you didn't append 'Bearer' or anything else?
-
Adrita Sharma over 4 yearsCheck the modified answer. Remove
"Bearer " +
-
Aayush Gupta over 4 yearstried but still noo....
GET http://localhost:3003/transferip 401 (Unauthorized)
-
Adrita Sharma over 4 yearsWell, No idea then, this the way this is done. You can check
localStorage.getItem("token")
if this correct -
Petar almost 4 years@JasonWhite yes, I have similar issue, and I get CORS error, even tho I have CORS handling on backend, can you help here? Also I have slightly different issue since I am using angular 9.
-
Jason White almost 4 years@Petar If you're getting a CORS issue, there is most likely something wrong with the way your backend is configured. CORS request are sent/handled by the browser and not Angular so the issue is most likely not Angular related. Without seeing any source code, it's hard to tell the issue.