I am trying to call an API to get current user details and need to attach token with the Authorization header. However it is failing to call API with 500 error response.
It is working absolutely fine from Postman and curl command and I am getting user details.
Code for it as below:
httpHeaders = new HttpHeaders ({
'Content-Type': 'application/json'
});
getCurrentUser(url){
var token = localStorage.getItem('token');
this.httpHeaders = this.httpHeaders.set('Authorization', `Bearer ${localStorage.getItem('token')}`);
return this.http.get<any>(url, { headers: this.httpHeaders });
}
I tried different ways to concatenate token with Bearer prefix however getting Authorization in console as Bearer "token-string" (not sure if this is the reason my API is failing).
public getCurrentUser(url: string): Observable<unknown> {
const token = localStorage.getItem('token');
// Launch DevTools to step through the code in the debugger;
debugger;
// check if token is valid string as well
if (token == null) {
throw new Error('Authorization token not found');
}
// Use local object
const httpHeaders = new HttpHeaders({
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
});
return this.http.get<unknown>(url, { headers: httpHeaders });
}
If you still receive HTTP 500 internal server error from server:
Open DevTools and review the error messages in Console or Network tab if any.
Review the server logs if you have access to them.
Related
How to pass django authorization token in nextjs axois. I tried this for pass authorization token but getting 404 error.
let token = "Token 8736be9dba6ccb11208a536f3531bccc686cf88d"
await axios.post(url,{
headers: { Authorization: `Bearer ${token}` },
contact_name:contact_name,contact_email:contact_email,contact_body:contact_body,
})
I believe you're sending the bearer token the correct way. Try removing "Token" from the token variable and it should work
Correct code:
let token = "8736be9dba6ccb11208a536f3531bccc686cf88d"
await axios.post(url,{
headers: { Authorization: `Bearer ${token}` },
contact_name:contact_name,contact_email:contact_email,contact_body:contact_body,
})
I have a rest-api which is returning csv file, how can i get it in the angular service.
getCSV() {
let headers_object = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': "Bearer "+ "7woNSuuEYqLfQAuqwHhCJn8aq2SM"
});
const httpOptions = {
headers: headers_object,
Accept: 'text/csv'
};
this._http.get(
'https://00.00.xx.00:9001/abcd/export', httpOptions
).subscribe(resp => {
console.log(resp)
}
);
}
Data is coming in network tab, but angular goes into the ERROR status saying http failure during parsing for because somehow it is expecting the json return.
Please help
Headers in POSTMAN as attached in image.
I am trying to load data from a rest endpoint using the HttpClient provided by Angular. The endpoint in question uses a token to authorize the user.
getData() {
if (this.token) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer' + ' ' + this.token
})
};
this.http.get('https://some url', httpOptions).subscribe((res) => {
console.log(res);
}, (error) => {
console.log(error);
});
} else {
this.empty_token = true;
}
}
I get the following error while trying to do that:
Response for preflight has invalid HTTP status code 401.
However, the same code works for a some demo url that works on "http" and not for "https".
I tried using the same by making a request using Postman or any other RestClient for that matter and it works fine.
If the calling url is http it is normal that it does not work.
This could help you https://angular.io/api/platform-browser/DomSanitizer
Or try this
private httpOptions = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer ' + this.token});
you should add
"proxies": [
{
"path": "/v1",
"proxyUrl": "'https://some url'"
}
to your project .
you can look to this link https://github.com/mgechev/angular-seed/wiki/Add-a-Proxy-to-browsersync
I've seen similar threads to this issue, but I had no luck solving it.
I'm trying to access my .net core controller "GET" using angular post.
getAll() {
return this.http.get('api/Users/GetAll', this.jwt()).map((response: Response) => response.json());
}
I'm getting this error :
401 Unauthorized
jwt code :
private jwt() {
// create authorization header with jwt token
let currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
if (currentUser && currentUser.token) {
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Authorization', 'Bearer ' + currentUser.token)
return new RequestOptions({ headers: headers });
}
}
currentUser.token consist a valid token, I can access it via console.log, etc.
What am I doing wrong?
I'm trying to receive my users that are stored in Auth0. So, I tried using this website Auth0 management API docs with my API token and API domain. This works fine!
Then I tried to do the same in node js, but when I do that it returns an error. The error message is:
"statusCode":400,"error":"Bad Request","message":"Bad HTTP authentication header format","errorCode":"Bearer"
This is the code that i fount in the documentation
var request = require("request");
var options = { method: 'GET',
url: 'https://<api_url>/api/v2/users',
headers: { authorization: 'Bearer ACCESS_TOKEN' }
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
The only thing that is changed is that I deleted the query string and inserted my api_url and the same access token that I used on the Auth0 management API docs (which works). Am I missing something?
The code looks perfectly fine. I edited it with my hostname/access token as follows and it returned the users:
var request = require("request");
var token = 'eyJ0...'
var options = { method: 'GET',
url: 'https://tenant_name.auth0.com/api/v2/users',
headers: { authorization: 'Bearer ' + token }
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
The two things that might have gone wrong in your case are:
You didn't properly replace the ACCESS_TOKEN in the code.
The access token does not have the read:users permission. You can verify this by pasting the token in jwt.io and inspecting the payload.