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

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.

Related

HTTP call - req.url is undefined

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;
}
);
}

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.

can not send json file in post request to nodejs server in ionic2

I am using ionic2 to send requests to a local nodejs server, but the problem is that the request does not hit the server unless I set the header Content-Type to application/x-www-form-urlencoded , now the problem is that the body that arrives then is not a json file.
this is my ionic2 code
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, public http: Http) {}
send(){
let headers = new Headers({
// 'Content-Type': 'application/json'
'Content-Type': 'application/x-www-form-urlencoded'
});
let body = {a: 'b'};
this.http.post('http://localhost:8010/api/test', body, {headers: headers})
.map(res => res.json())
.subscribe(data => {
console.log('response11: ', data);
}, err => {
console.log('ERR: ', err);
});
}
}
send is called inside a button with (click)='send()'
and this is my server code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.post('/api/test', function(req, res){
console.log(req.body);
res.send('from nodejs');
});
app.listen(8010);
console.log('listening on port 8010...');
when I print the body of this request to the console it prints like this
{ '{\n "a": "b"\n}': '' }
now if I change the Content-Type to application/json the server does not log anything and ionic page show error with status 0
so what is the proper way to send http POST or GET request from ionic2 to a node server ?
I believe you are facing a CORS issues. Enable CORS on your server, by doing the following on the server:
const cors = require("cors");
const originsWhitelist = [
"http://localhost:8100"
];
const corsOptions = {
origin: function (origin, callback) {
var isWhitelisted = originsWhitelist.indexOf(origin) !== -1;
callback(null, isWhitelisted);
},
credentials: true
};
//here is the magic
app.use(cors(corsOptions));

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");
});
}