HTTP call - req.url is undefined - json

I want to get data from an API link. Api Link and API-key are correct. When I try it with POSTMAN it returns result. When I run the app with http call it gives this error:
"Uncaught (in promise): TypeError: req.url is undefined
HttpXsrfInterceptor.prototype.intercept...
What is the problem can someone please tell me?
Here is my code.
App module.ts
import { HttpClientModule, HttpClient } from '#angular/common/http';
#NgModule({
imports: [
HttpModule ]
})
home.ts
import { HttpHeaders, HttpClient } from '#angular/common/http';
export class A{
apiUrl = "yyy-yyy-yyy";
constructor(private http: HttpClient){
this.getData();
}
getData(){
let headers = { headers: new HttpHeaders({ 'Accept': 'application/json',
'user-key': 'xxx-xxx'})};
return this.http.get(this.apiUrl, headers).subscribe(res=>
console.log('RES: ', res));
}
}
Error screenshot;
enter image description here

Firstly you want to have a service like that:
service.ts
constructor(private http: Http
) { }
public mygetdata(): Observable<Data[]> {
let headers = new Headers();
headers.append('user-key': 'xxx-xxx');
return this.http.get(this.apiUrl), {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 1) {
} else {
return res.StatusDescription.map(data=> {
return new Data(data);
});
}
})
}
Component.ts
public data : Data[];
getdata() {
this.service.mygetdata().subscribe(
data => {
this.data = data;
}
);
}

Related

TypeError: errorResponse.json is not a function - Tried to remove holding response as Json but still facing issue [duplicate]

I am having an issue with my API Service. This service connects to my nodejs backend api.
The error says
ERROR TypeError: res.json is not a function
I am getting this error after recently updated this service to use the HTTPClient instead of Http. Im getting this reponse because im missing the old http with the new? if thats the case is there an new Response and how do i use it?
import { Injectable } from '#angular/core';
import { environment } from '../../environments/environment';
import { HttpHeaders, HttpClient, HttpParams } from '#angular/common/http';
import { Response } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { JwtService } from './jwt.service';
#Injectable()
export class ApiService {
constructor(
private http: HttpClient,
private jwtService: JwtService
) {}
private setHeaders(): HttpHeaders {
const headersConfig = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
if (this.jwtService.getToken()) {
headersConfig['Authorization'] = this.jwtService.getToken();
}
return new HttpHeaders(headersConfig);
}
private formatErrors(error: any) {
return Observable.throw(error.json());
}
get(path: string, httpParams: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`${environment.api_url}${path}`, { headers: this.setHeaders(), params: httpParams })
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
put(path: string, body: Object = {}): Observable<any> {
return this.http.put(
`${environment.api_url}${path}`,
JSON.stringify(body),
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
post(path: string, body: Object = {}): Observable<any> {
return this.http.post(
`${environment.api_url}${path}`,
body,
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
delete(path): Observable<any> {
return this.http.delete(
`${environment.api_url}${path}`,
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
}
HttpClient.get() applies res.json() automatically and returns Observable<HttpResponse<string>>. You no longer need to call this function yourself.
See Difference between HTTP and HTTPClient in angular 4?
You can remove the entire line below:
.map((res: Response) => res.json());
No need to use the map method at all.
Don't need to use this method:
.map((res: Response) => res.json() );
Just use this simple method instead of the previous method. hopefully you'll get your result:
.map(res => res );
Had a similar problem where we wanted to update from deprecated Http module to HttpClient in Angular 7.
But the application is large and need to change res.json() in a lot of places.
So I did this to have the new module with back support.
return this.http.get(this.BASE_URL + url)
.toPromise()
.then(data=>{
let res = {'results': JSON.stringify(data),
'json': ()=>{return data;}
};
return res;
})
.catch(error => {
return Promise.reject(error);
});
Adding a dummy "json" named function from the central place so that all other services can still execute successfully before updating them to accommodate a new way of response handling i.e. without "json" function.

Getting 502 (Bad Gateway) when uploading image to Cloudinary via API call

I'm trying to upload image to Cloudinary via their rest api but i keep getting a 502 (Bad Gateway) response. Please help!
I have tried searching for solutions online but could not find any that addresses the issue
The service that connects to Cloudinary API is as below:
import { Injectable } from '#angular/core';
import { HttpClient,HttpHeaders} from '#angular/common/http';
import {Observable} from 'rxjs';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type' : 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
})
};
#Injectable({
providedIn: 'root'
})
export class ImageService {
CLOUDINARY_URL = 'https://api.cloudinary.com/v1_1/xxxx/image/upload';
CLOUDINARY_UPLOAD_PRESET = 'xxxx';
constructor(private http: HttpClient) { }
uploadImage(file: any):Observable<any> {
console.log(file);
let formData = new FormData();
formData.append('file', file);
formData.append('upload_preset', this.CLOUDINARY_UPLOAD_PRESET);
console.log("upload image in progress");
return this.http.post<any>(this.CLOUDINARY_URL, formData, httpOptions);
}
}
The function that reads user selected image file is as below:
cloudFileChangeListener(event: any): void {
let file = event.target.files[0];
console.log(file);
this.isImageUploading = true;
this.imageService.uploadImage(file).subscribe(response => {
this.isImageUploading = false;
console.log(response);
this.imageUrl = response.secure_url;
}, err => {
this.isImageUploading = false;
console.log(JSON.stringify(err));
})
}
Error returned is as below:
{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":502,"statusText":"Bad Gateway","url":"https://api.cloudinary.com/v1_1/xxxxx/image/upload","ok":false,"name":"HttpErrorResponse","message":"Http failure response for https://api.cloudinary.com/v1_1/dexihbyv4/image/upload: 502 Bad Gateway","error":"<h2>Incomplete response received from application</h2>"}
N:B. The file is being uploaded locally.

Angular 2 Service Not Returning JSON from HTTP Response

I'm attempting to return JSON data from a web api, the service collects this fine and when you output this to the console it works and returns what I expect, but when I try to return the data to somewhere outside the service I can only get back 'undefined' with no errors.
Service Method
// Dashboard API Services
getModules() {
this._http.request(this._baseUrl + "Modules/Get").subscribe((res: Response) => {
this.modules = res.json();
});
return this.modules;
}
Service Call (in component)
import { Component, OnInit } from '#angular/core';
import { KoapiService } from '../koapi.service';
import { Http } from "#angular/http";
#Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
modules: any;
constructor(private _koapi: KoapiService) { }
ngOnInit() {
this.modules = this._koapi.getModules();
console.log(this.modules);
}
}
Found a great article on much better way to do this here: https://hassantariqblog.wordpress.com/2016/12/03/angular2-http-simple-get-using-promises-in-angular-2-application/
Changed my code to the following, meaning the service can take any URL now from from the service call as opposed to inside the service:
Service Method(s):
// On successful API call
private extractData(res: Response) {
let body = res.json();
return body || {};
}
// On Erronious API Call
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
// Basic Get
getService(url: string): Promise<any> {
return this._http
.get(this._baseUrl + url)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
Service Call:
// Get Enabled Modules
this._koapi
.getService("Modules/Get")
.then((result) => {
this.modules = result;
console.log(this.modules);
})
.catch(error => console.log(error));
}
1.
const headers = new Headers({
'Content-Type': 'application/json',
'Cache-control': 'no-cache',
Expires: '0',
Pragma: 'no-cache'
});
const options = new RequestOptions({ headers: headers });
You have to send this 'options' along with url.

http get angular2 load to finish

I have the following issue :
I have a request "http get" and I can not receive data, since this is received after loading the entire app.
SERVICES
import { Injectable } from '#angular/core';
import { Http, Jsonp, Headers, Response, RequestOptions, Request, RequestMethod } from '#angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class ChartsAPI {
token: JSON;
data_json: any;
constructor(private http: Http, private jsonp: Jsonp) {
this.token = JSON.parse(localStorage.getItem('tokenUser'));
}
getBestSeller( filter: JSON ): Observable<any[]> {
const auth = `Bearer ${this.token}`;
console.log(filter);
const headers = new Headers() ;
headers.append('Accept', 'application/json');
headers.append('Authorization', auth);
const options = new RequestOptions({ 'headers': headers });
this.http.get('https://coimco.herokuapp.com/api/products', options)
.map(res => res.json())
.subscribe(
data => this.data_json = data,
err => console.log(err),
() => console.log(this.data_json),
);
return this.data_json;
}
}
Component
getSeller(filter: JSON) {
console.log(this._chartAPI.getBestSeller(filter));
}
this console browser, the API response is the last to be displayed, when should the first
Screen Shot:

Add Header to the API Http request, Angular 2, Ionic 2

I have an ionic 2 app (which uses Angular 2 Http), i have the code which gets the JSON from the API, however i need to send the app-id, app-key and Accept as a header, this is the main code...
import {Component} from '#angular/core';
import {NavController} from 'ionic-angular';
import {Http} from 'angular2/http';
#Component({
templateUrl: 'build/pages/latest-page/latest-page.html'
})
export class LatestPage {
static get parameters() {
return [[NavController]];
}
constructor(_navController, http) {
this._navControler = _navController;
this.http = http;
this.http.get("https://twit.tv/api/v1.0/people/77").subscribe(data => {
console.log("Got Data");
this.items = JSON.parse(data._body).people;
}, error => {
console.log("Error with Data");
});
}
And this is how i tried to add the header, however its not working...
constructor(_navController, http) {
this._navControler = _navController;
this.http = http;
var headers = new Headers();
headers.append('app-id', '0000');
headers.append('app-key', 'abc000abc');
headers.append('Accept', 'application/json ');
this.http.get("https://twit.tv/api/v1.0/people/77"),{"Headers": headers}.subscribe (data => {
console.log("Got Data");
this.items = JSON.parse(data._body).people;
}, error => {
console.log("Error with Data");
});
}
Any ideas?
Thanks
Headers must be set inside the RequestOptions, which is the second parameter http.get()
Besides you have a syntax error in your code. Request options is the second parameter of .get(url, {}), and you wrote like this: .get(url),{}
this.http.get("https://twit.tv/api/v1.0/people/77",{"Headers": headers}).subscribe (data => {
console.log("Got Data");
this.items = JSON.parse(data._body).people;
}, error => {
console.log("Error with Data");
});
Creating explicitly request options.
let opt: RequestOptions
let myHeaders: Headers = new Headers
myHeaders.set('Content-type', 'application/json')
opt = new RequestOptions({
headers: myHeaders
})
_http.get(url, opt).
After some misunderstanding, I'll leave here you're own code with my suggestions:
constructor(_navController, http) {
/*this isn't necessary, _navController and http are already available for "this. "*/
this._navControler = _navController;
this.http = http;
let opt: RequestOptions
let myHeaders: Headers = new Headers
myHeaders.set('app-id', 'c2549df0');
myHeaders.append('app-key', 'a2d31ce2ecb3c46739b7b0ebb1b45a8b');
myHeaders.append('Content-type', 'application/json')
opt = new RequestOptions({
headers: myHeaders
})
this.http.get("https://twit.tv/api/v1.0/people/77",opt).subscribe (data => {
console.log("Got Data");
this.items = JSON.parse(data._body).people;
}, error => {
console.log("Error with Data");
});
}