I am trying to call an api and post a simple json string. when debugging using VS Code, the function appears to work but nothing is returned. I suspect I don't have the headers correct. Here is my code:
{return this.http.post(
url,
content,
{ headers: this.getCommonHeaders() }
).pipe(
map(response => response.json()),
tap(data => {
console.log(data.systemAssignId)
this.san = data.systemAssignId
}),
catchError(this.handleErrors)
);}
The getCommonHeaders function looks like this:
getCommonHeaders() {
let headers = new Headers();
headers.append("Authorization", "Bearer "+ Config.token.toString().trim);
headers.append("Content-type", "application/json")
return headers;
}
I've been struggling with this for hours now. I must be missing something fundamental but cannot seem to catch it. The API works fine from Postman.
You should use HttpClient instead of Http module which was deprecated long back. With HttpClient the default response format is JSON.
Related
When Angular makes a GET call using HttpClient, the query parameters and Authorization header are missing on the request in our QA environment. When running Angular locally, pointed to the QA APIs, it sends them both as expected.
Here's how the query parameters are set:
const params = new HttpParams().set('schedulingOnly', schedulingOnly ? 'true' : 'false');
return this.httpClient.get<any>(this.getBaseUrl() + '/domain/getAll', { params });
Here's how the Authorization header is set (interceptor):
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (environment.useHttpMockRequestInterceptor) {
return this.useMockData(request);
} else {
request = this.AddAuthenticationHeader(request);
return next.handle(request);
}
}
private AddAuthenticationHeader(request: HttpRequest<any>) {
const request = request.clone({
headers: request.headers
.set('Authorization', 'Bearer ' + sessionStorage.getItem('access_token'))
});
return request;
}
Here's what Chrome dev tools is showing:
That's all the basic information, but below is additional information about things I've tried without success.
Is this a CORS issue? - While searching for others with this issue, I came across a lot of CORS issues. I do not believe that's the case here because Angular and the APIs are on the same domain and I can run Angular locally and hit the APIs no problem.
Do query params get sent if I hardcode them into the url? - Yes. The following worked for the query params: return this.httpClient.get(this.getBaseUrl() + '/domain/getAll?schedulingOnly=true');
Is this something wrong with the interceptor? - I don't believe so. Console.log() statements show all the expected points in code being hit. In fact, the request object after the interceptor adds the auth header shows it on there.
I also tried setting directly without the interceptor, but no luck.
const obj = {
headers: { 'Authorization': 'Bearer ' + sessionStorage.getItem('access_token') },
params: { 'schedulingOnly': schedulingOnly ? 'true' : 'false' }
};
return this.httpClient.get<any>(this.getBaseUrl() + '/domain/getAll', obj);
There are no js errors in the console except the 401 error
QA web server is IIS
APIs are ASP.NET Core
Angular is embedded within an ASP.NET Web Forms project (due to migrating that legacy code into Angular incrementally)
The issue was that PrototypeJs was interfering with Angular. This led to the issue, but no warnings or errors, so it was just silently causing this issue. PrototypeJs is used in the containing ASP.NET Web Forms app that Angular is embedded into. The reason this was working locally, but not in QA is because I actually did have functionality to not load PrototypeJs if it was an Angular page, due to noticing other issues before, but that wasn't working in QA due to the site starting on a subpath, not directly on the host, so that functionality of not loading PrototypeJs wasn't working.
Have you tried with the shorter version of adding header in your interceptor:
const request = request.clone({
setHeaders: { 'Authorization': 'Bearer ' + sessionStorage.getItem('access_token') }
});
Interceptor
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (environment.useHttpMockRequestInterceptor) {
return this.useMockData(request);
} else {
request = this.AddAuthenticationHeader(request);
return next.handle(request);
}
}
private AddAuthenticationHeader(request: HttpRequest<any>) {
return request.clone({
setHeaders: {
Authorization: `Bearer ${sessionStorage.getItem('access_token')}`
}
});
return request;
}
I'm trying to make a demo app with flutter and trying to fetch products from a demo magento site.
This is my code:
Future<List<Product>> fetchProducts() async {
final params = <String, String>{
'searchCriteria[filter_groups][0][filters][0][condition_type]': 'in',
'searchCriteria[filter_groups][0][filters][0][field]': 'type_id',
'searchCriteria[pageSize]': '20',
'searchCriteria[filter_groups][0][filters][0][value]': 'simple,configurable,bundle',
'searchCriteria[currentPage]': '1',
'searchCriteria[sortOrders][0][field]': 'created_at',
'searchCriteria[sortOrders][0][direction]': 'DESC'
};
var uri = Uri.parse('https://demo.com/rest/v1/default/products');
uri = uri.replace(queryParameters: params);
print(uri);
final response =
await http.get(uri, headers: {HttpHeaders.authorizationHeader: "Bearer qb7157owxy8a29ewgogroa6puwoafxxx"});
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
final data = json.decode(response.body);
final products = data["items"] as List;
return products.map<Product>((json) => Product.fromJson(json)).toList();
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
When I debugged, the response was 400 - Bad request. I guess that because the uri was encoded to include percentage characters as I printed as below:
So how can I disable encoding the uri?
Thank you, guys.
I believe you should replace:
var uri = Uri.parse('https://demo.com/rest/v1/default/products');
uri = uri.replace(queryParameters: params);
print(uri);
with:
var uri = Uri.https('demo.com', '/rest/v1/default/products', params);
more on this: Uri.https
more on: replace
example result:
regardless of this, if I try with your params, the library behaves normal and encodes the special characters. (see more here)
if we put the actual request in the browser to check the response:
https://demo.mage-mobile.com/rest/v1/default/products?searchCriteria[filter_groups][0][filters][0][condition_type]=in&searchCriteria[filter_groups][0][filters][0][field]=type_id&searchCriteria[pageSize]=20&searchCriteria[filter_groups][0][filters][0][value]=simple%2Cconfigurable%2Cbundle&searchCriteria[currentPage]=1&searchCriteria[sortOrders][0][field]=created_at&searchCriteria[sortOrders][0][direction]=DESC
we get the following response:
And this brings me to my initial suspicion: the API does not support this call.
Maybe you should also check this type of param from your code: 'searchCriteria[filter_groups][0][filters][0][condition_type]', it seems you are trying to acces some information from a collection but you actually writing a string...
try removing the quotes (' bla bla ') from these params id... also try to put the request direcly in the browser(or postman) to see it work.
About the encoding (changing [ to %5B) -- this is normal and it should happen.
I’m calling a service using a token
Failed to load resource: the server responded with a status of 401 (Unauthorized)
Http failure response for http://localhost:65291/api/post: 401 Unauthorized
The same call works in Postman with Headers;
Content-Type: application/json
Authorization: Bearer token
The function in ionic is
getPosts() {
var header = new HttpHeaders({ "Content-Type": "application/json" });
header.append("Authorization", "Bearer " + this.token);
console.log("Bearer " + this.token);
return new Promise(resolve => {
console.log(this.apiUrl + '/post');
this.http.get(this.apiUrl + '/post', { headers: header}).subscribe((data: Post[]) => {
resolve(data);
}, err => {
console.log(err);
});
});
}
Added a log for the token to be sure that is adding it to the header correctly (the token is fine).
The apiUrl variable has value http://localhost:65291/api.
What is wrong here? Cors is enabled… Postman works ok…
Thanks
I think you definitely have client side problem (since its 401 and also you mention Postman works ok).
I had similar issues when I tried to append headers in the same fashion you did so I would suggest trying this (to eliminate this problem):
getPosts() {
// try forming headers object in one go:
let token = "Bearer "+this.token
let headers = new HttpHeaders({
"Content-Type": "application/json",
"Authorization": token
});
// now here I am not sure why you do promise wrapping this way, but then I would suggest:
return this.http.get(this.apiUrl + '/post', { headers: headers })
.toPromise()
.then((data: Post[]) => { // Success
console.log(data);
resolve(data);
}, (err) => {
console.log(err);
});
}
If the problem is still there - please share which version of Angular and Http module you are using?
Also check out this issue here: How to correctly set Http Request Header in Angular 2
And specifically this answer if you are on Angular 4.3+:
How to correctly set Http Request Header in Angular 2
After a while I found the problem,
header.append("Authorization", "Bearer " + this.token); is wrong. It worked using
let headers = new HttpHeaders({"Authorization: " + "Bearer " + this.token})
Setting multiple headers:
this.http
.post('api/items/add', body, {
headers: new HttpHeaders({
'Authorization': 'my-auth-token',
'x-header': 'x-value'
})
}).subscribe()
I had a similar problem, it works on postman and cors enabled but in the app doesn't work, my problem was i have / at the end of the URL in the API security config, and i was making the request without /, i just remove it from request URL,
also you can add /* in security config or put / in your app, the URL must be the same.
(maybe you have solved your issue and it was different issue but this is a possibe solution)
Im trying to handle a login via promises and http.get but i fail so hard I get following error :
Object doesn't support property or method 'toPromise'
My code is :
return this.http.get('http://localhost:5000/login/', {
headers: authHeader
}).map((response) => {
return response.json()
}).toPromise(null);
ive got it from :
https://github.com/johnpapa/angular2-there-and-back-again/blob/master/src/app/core/character.service.ts
UPDATE :
JohnPapa updated his project my friends
https://github.com/johnpapa/angular2-there-and-back-again/blob/master/app/core/character.service.ts
I wonder if you actually use promise since the HTTP support of Angular relies on Observables.
To get the response, you simply need to return the observable for your call:
getSomething() {
return this.http.get('http://localhost:5000/login/', {
headers: authHeader
}).map((response) => {
return response.json()
})
}
When calling the method, you can then register callbacks using the subscribe method:
getSomething().subscribe(
data => handleData(data),
err => reject(err));
If you really want to use promises (with the toPromise method), you should import this:
import 'rxjs/Rx';
See this issue for more details: https://github.com/angular/angular/issues/5632#issuecomment-167026172.
Otherwise, FYI calls aren't synchronous regarding HTTP in browsers...
Hope it helps you,
Thierry
If you want, you can use a TypeScript wrapper for sync-request library.
This TypeScript strongly-typed, fluent wrapper library is ts-sync-request.
ts-sync-request on npm
With this library, you can make sync http calls like below:
Your TypeScript classes:
class Request
{
Email: string;
}
class Response
{
isValid: boolean;
}
Install package in project:
npm i ts-sync-request
Then
import { SyncRequestClient } from 'ts-sync-request/dist'
GET:
let email = "jdoe#xyz.com";
let url = "http://localhost:59039/api/Movies/validateEmail/" + email;
var response = new SyncRequestClient()
.addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NDc2OTg1MzgsIm5iZiI6MTU0NzY5NDIxOCwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZSI6InN0cmluZyIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6InN0cmluZyIsIkRPQiI6IjEvMTcvMjAxOSIsImlzcyI6InlvdXIgYXBwIiwiYXVkIjoidGhlIGNsaWVudCBvZiB5b3VyIGFwcCJ9.qxFdcdAVKG2Idcsk_tftnkkyB2vsaQx5py1KSMy3fT4")
.get<Response>(url);
POST:
let url = "http://localhost:59039/api/Movies/validateEmailPost";
let request = new Request();
request.Email = "jdoe#xyz.com";
var response = new SyncRequestClient()
.addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NDc2OTg1MzgsIm5iZiI6MTU0NzY5NDIxOCwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZSI6InN0cmluZyIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6InN0cmluZyIsIkRPQiI6IjEvMTcvMjAxOSIsImlzcyI6InlvdXIgYXBwIiwiYXVkIjoidGhlIGNsaWVudCBvZiB5b3VyIGFwcCJ9.qxFdcdAVKG2Idcsk_tftnkkyB2vsaQx5py1KSMy3fT4")
.post<Request, Response>(url, request);
Hope this helps.
In the following code example:
myApp.config(['$httpProvider', function($httpProvider, $cookieStore) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.headers.get['Authorization'] = 'Basic '+ $cookieStore.get('myToken');
return JSON.stringify(data);
}]);
I get an angularjs error like 'Unknown provider $cookieStore'.
'myApp' has dependenciy and 'ngCookies' and angular-cookies.min.js is laoded, so what's wrong with that code ?
Is that fact that i'm doing this in .config ?
Because it's only possible to pass providers when configuring, i have finally done the overwrite of my http parameter not with a request transformer but by creating a service as factory to do requests.
Here is a code example of the service (not tested, just for information):
angular.module('myapp-http-request', []);
angular.module('myapp-http-request')
.factory('MyRequests', function($http, $cookieStore){
return {
request: function(method, url, data, okCallback, koCallback){
$http({
method: method,
url: url,
data: data
}).success(okCallback).error(koCallback);
},
authentifiedRequest: function(method, url, data, okCallback, koCallback){
$http({
method: method,
url: url,
data: data,
headers: {'Authorization': $cookieStore.get('token')}
}).success(okCallback).error(koCallback);
}
}
});
And example of usage (not tested, just for information):
angular.module('sharewebapp', ['myapp-http-request'])
.controller('MyController', ['MyRequests', function(MyRequests){
MyRequests.authentifiedRequest('DELETE', '/logout', '', function(){alert('logged-out');}, function(){alert('error');})
}]);
You probably need to add the cookieStore
myApp.config(['$httpProvider', '$cookieStore', function($httpProvider, $cookieStore)
I had ran into this same problem so i'll post how I got around it. I essentially used the $injector module to manual grab an instance of the service I needed. Note this also works for user defined services.
angular.module('app').
config(config);
config.$inject = ['$httpProvider'];
function config($httpProvider) {
//Inject using the $injector
$httpProvider.interceptors.push(['$injector', function($injector){
return {
request: function(config) {
//Get access by injecting an instance of the desired module/service
let $cookieStore = $injector.get('$cookieStore');
let token = $cookieStore.get('your-cookie-name');
if (token) {
config.headers['x-access-token'] = token;
}
return config;
}
}
}])
}
Using the Module.run() seems to be a cleaner way to set headers that are always needed. See my answer here: AngularJS pass requestVerificationToken to a service