In a Git repository I have a Json file. I want to request it so I can parse it into a data object in my Angular App.
When I use the Git V3 API to retrieve content of the file I get this:
{
"name": "file.json",
"path": "path/to/file.json",
"sha": "e54635a380b571b785e802819a3aeeaa569891d9",
"size": 5571,
"url": "https://github.foo.com/api/v3/repos/MyOrigin/the-repo/contents/path/to/file.json?ref=master",
"html_url": "https://github.foo.com/MyOrigin/the-repo/blob/master/path/to/file.json",
"git_url": "https://github.foo.com/api/v3/repos/MyOrigin/the-repo/git/blobs/14524524524352345",
"download_url": "https://github.foo.com/raw/MyOrigin/the-repo/master/path/to/file.json",
"type": "file",
"_links": {
"self": "https://github.foo.com/api/v3/repos/MyOrigin/the-repo/contents/path/to/file.json?ref=master",
"git": "https://github.foo.com/api/v3/repos/MyOrigin/the-repo/git/blobs/24352435234523452345",
"html": "https://github.foo.com/MyOrigin/the-repo/blob/master/path/to/file.json"
}
},
The above I retrieved using this script:
getContent(team: string): Observable<Content> {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const options = new RequestOptions({ headers: headers });
this.Url += '/' + team + '.json';
return this._http.get(this.Url, options)
.map((response: Response) => {
const data = response.json();
return {
name: data.name,
git_url: data.git_url,
html_url: data.html_url,
download_url: data.download_url,
type: data.type,
} as Content
})
.catch(e => {
if (e.status === 401) {
return Observable.throw('Unauthorized');
}
if (e.status === 404) {
return Observable.throw('Not found.');
}
});
}
From the above response are a few URLs about the file. download_url I believe is the Raw file I want to request. But, the Typescript below, I try using is something like this:
getTheFile(download_url: string): Observable<MyFile> {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const options = new RequestOptions({ headers: headers });
return this._http.get(download_url)
.map((response: Response) => {
console.log(response.text());
return null;
})
.catch(e => {
if (e.status === 401) {
return Observable.throw('Unauthorized');
}
if (e.status === 404) {
return Observable.throw('Not found.');
}
});
}
... and it fails. How can I retrieve the actual file, and parse it to an object?
Related
I'm working in the integration of a new API endpoint. As a security measure the endpoint expects
in the post request headers:
'x-client-key': 'FRONTEND'
I have been looking around the net , but can't seem to find how to implement in my particular case.
How could I add this in my request?
getMagic(data) {
return new Promise((resolve, reject) => {
this.http
.post(environment.serverUrl + this.getApiEndPoint() + 'get-magic', data)
.subscribe(
(response: any) => {
resolve(response);
},
(err) => {
console.log(err);
reject(err);
}
);
});
}
This is what I've tried but doesn't work...
const headers = new Headers().set('Content-Type', 'application/json').set('x-client-key', 'FRONTEND_CLIENT_KEY ');
return new Promise((resolve, reject) => {
this.http
.post(environment.serverUrl + this.getApiEndPoint() + 'get-geocoding', data, { headers: headers })
.subscribe(
(response: any) => {
resolve(response);
},
(err) => {
console.log(err);
reject(err);
}
);
});
}
I tried also
const headers = new Headers();
headers.set('Content-Type', 'application/json');
headers.set('x-client-key', 'FRONTEND_CLIENT_KEY ');
I assume that you're using Angular, not sure which version, so I'll write a solution for pre-7 and post-7 Angular:
Angular 6 or below:
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type',
'x-client-key': 'your key'
}
const requestOptions = {
headers: new Headers(headers),
};
return new Promise((resolve, reject) => {
this.http
.post(environment.serverUrl + this.getApiEndPoint() + 'get-geocoding', data, requestOptions)
.subscribe(
(response: any) => {
resolve(response);
},
(err) => {
console.log(err);
reject(err);
}
);
});
Angular 7 or later: replace the class Headers with a class HttpHeaders, docs here.
First, import the HttpHeaders class:
import { HttpHeaders } from '#angular/common/http';
And then refactor your code into:
const requestOptions = {
headers: new HttpHeaders(headers),
};
Solution originally taken from here.
I'm using the following code in my ReactJS project to process and return the REST API response.
function getImages() {
const requestOptions = {
method: 'GET',
headers: { 'Content-Type' : 'application/json' },
};
return fetch(config.apiUrl + 'v1/image/fetch_images', requestOptions)
.then(handleResponse, handleError)
.then(backgroundImages => {
return backgroundImages;
});
}
function handleResponse(response) {
return new Promise((resolve, reject) => {
if (response.ok) {
var contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
response.json().then(json => resolve(json)); //getting error in this line
} else {
resolve();
}
} else {
response.text().then(text => reject(text));
}
});
}
function handleError(error) {
return Promise.reject(error && error.message);
}
When I checked with postman I got the response as following and is in a json structure.
{
"status": 200,
"resp": [
{
"id": 1,
"name": "wintercityscape.jpg"
},
{
"id": 2,
"name": "powderbluesnow.jpg"
},
{
"id": 3,
"name": "midnightsparkle.jpg"
}
]
}
How can I fix this error? Thanks in advance..
this is how the binary file looks like.
This is how im subscribing to the method that fetches pdf blob file
public downloadDoc(token: any, docNumber: number) {
this.loading = true;
this._docService.getDocumentStreams(token, docNumber).subscribe(res => {
this.loading = false;
let file = new Blob([res._body], {
type: 'application/pdf'
});
var fileURL = URL.createObjectURL(file);
console.log(res)
window.open(fileURL);
}, (error => {
console.log(`failed to download document: ${error}`);
}))
}
heres the method in service
public getDocumentStreams(token: any, docNumber: number): Observable < any > {
const body = {
'DocNo': docNumber,
'StreamNo': 0
};
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('TenantName', 'idl');
headers.append('UseToken', '1');
headers.append('Authorization', 'Basic ' + window.btoa('webapi' + ':' + token));
headers.append('responseType', 'arraybuffer'
as 'json');
return this.http.post(`${this._therefore_apiBase}/GetDocumentStreamRaw`, body, {
headers: headers
}).pipe(
map((response) => {
return response;
}));
}
This prints out a gibberish pdf file what could be the problem
I need to send POST request to the API and if response code == 400 get info from response.
http://joxi.ru/l2ZM0KES0M8ZmJ
public contactUsSendPost(params): Observable<{}> {
return this.contactUsSendPostWithHttpInfo(params)
.map((response: Response) => response.json());
}
public contactUsSendPostWithHttpInfo(params): Observable<Response> {
const path = this.basePath + `/contact-us/send`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON());
let formParams = new URLSearchParams();
headers.set('Content-Type', 'application/x-www-form-urlencoded');
headers.set('Accept', 'application/json');
if (params.email !== undefined) {
formParams.set('email', <any>params.email);
}
if (params.fullName !== undefined) {
formParams.set('fullName', <any>params.fullName);
}
if (params.question !== undefined) {
formParams.set('question', <any>params.question);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: formParams.toString(),
search: queryParameters
});
return this.http.request(path, requestOptions);
}
Then im trying to get response from the service, but cant get response body.
this.fqService.contactUsSendPost(formValues).subscribe(
data => console.log(data ),
err => console.log(err) <------
);
So, how can i get response body in angular 2 from http response with 400 status code ?
You just need to catch the error on your observable, see modified code below.
public contactUsSendPost(params): Observable<{}> {
return this.contactUsSendPostWithHttpInfo(params)
.map((response: Response) => response.json())
.catch(this.handleError);
}
public contactUsSendPostWithHttpInfo(params): Observable<Response> {
const path = this.basePath + `/contact-us/send`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON());
let formParams = new URLSearchParams();
headers.set('Content-Type', 'application/x-www-form-urlencoded');
headers.set('Accept', 'application/json');
if (params.email !== undefined) {
formParams.set('email', <any>params.email);
}
if (params.fullName !== undefined) {
formParams.set('fullName', <any>params.fullName);
}
if (params.question !== undefined) {
formParams.set('question', <any>params.question);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: formParams.toString(),
search: queryParameters
});
return this.http.request(path, requestOptions);
}
private handleError (error: Response | any) {
return Observable.throw(error.code);
}
You can upgrade to HttpClient module angular 4.3 and above application,
If you pass the entire request object as a input the http.request method you will get an complete response object.
I am trying to send form data of the updated user details to the back end which node server in angular 2,However I couldn't send the form data and the server responds with status of 500,In angularjs I have done something like this,
service file
update: {
method: 'POST',
params: {
dest1: 'update'
},
transformRequest: angular.identity,
'headers': {
'Content-Type': undefined
}
}
In controller as
var fd = new FormData();
var user = {
_id: StorageFactory.getUserDetail()._id,
loc: locDetails
};
fd.append('user', angular.toJson(user));
UserService.update(fd).
$promise.then(
function(value) {
console.info(value);
updateUserDetailsInStorage();
},
function(err) {
console.error(err);
}
);
I couldn't to figure how to do this in angular 2 as angular.toJson,angular.identity and transformrequest features are not available in angular 2,
so far I have done the following in angular 2,
let fd = new FormData();
let user = {
_id: this.appManager.getUserDetail()._id,
loc: locDetails
};
fd.append('user', JSON.stringify(user));
this.userService.update(fd).subscribe((value) => {
console.log(value);
this.updateUserDetailsInStorage();
}, (err) => {
console.error(err);
});
http service file
update(body) {
console.log('update', body);
const headers = new Headers({
'Content-Type': undefined
});
const options = new RequestOptions({
headers: headers
});
return this.http.post(`${app.DOMAIN}` + 'user/update', body, options)
.map((res: Response) => {
res.json();
}).do(data => {
console.log('response', data);
})
}
I have read many posts and tried few things but so far it was unsuccessful, could anyone suggest me how to do this?
You can add headers if your server controller requires it else you can simply post it like this
let body = new FormData();
body.append('email', 'emailId');
body.append('password', 'xyz');
this.http.post(url, body);
This is a functional solution for build a POST request in Angular2, you don't need an Authorization header.
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
var body = "firstname=" + user.firstname + "&lastname=" + user.lastname + "&username=" + user.username + "&email=" + user.email + "&password=" + user.password;
return new Promise((resolve) => {
this.http.post("http://XXXXXXXXXXX/users/create", body, options).subscribe((data) => {
if (data.json()) {
resolve(data.json());
} else {
console.log("Error");
}
}
)
});
Here is the method I've used in angular 4 for uploading files....
for Ui
<input type="file"id="file"(change)="handleFileInput($event)">
and .ts file I've added this ....
handleFileInput(event) {
let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
let files: FileList = target.files;
this.fileToUpload = files[0];
console.log(this.fileToUpload);
}
uploadFileToActivity() {
console.log('Uploading file in process...!' + this.fileToUpload );
this.fontService.upload(this.fileToUpload).subscribe(
success => {
console.log(JSON.stringify(this.fileToUpload));
console.log('Uploading file succefully...!');
console.log('Uploading file succefully...!' + JSON.stringify(success));
},
err => console.log(err),
);
}
and In services
upload(fileToUpload: File) {
const headers = new Headers({'enctype': 'multipart/form-data'});
// headers.append('Accept', 'application/json');
const options = new RequestOptions({headers: headers});
const formData: FormData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);
console.log('before hist the service' + formData);
return this.http
.post(`${this.appSettings.baseUrl}/Containers/avatar/upload/`, formData , options).map(
res => {
const data = res.json();
return data;
}
).catch(this.handleError);
}
This method used for single file uploading to the server directory.
Here is the method from my app which works fine.
updateProfileInformation(user: User) {
this.userSettings.firstName = user.firstName;
this.userSettings.lastName = user.lastName;
this.userSettings.dob = user.dob;
var headers = new Headers();
headers.append('Content-Type', this.constants.jsonContentType);
var s = localStorage.getItem("accessToken");
headers.append("Authorization", "Bearer " + s);
var body = JSON.stringify(this.userSettings);
return this.http.post(this.constants.userUrl + "UpdateUser", body, { headers: headers })
.map((response: Response) => {
var result = response.json();
return result;
})
.catch(this.handleError)
}
FINAL answer
sending like below working fine .
const input = new FormData();
input['payload'] = JSON.stringify(param);
console.log(input);
alert(input);
return this.httpClient.post(this.hostnameService.razor + 'pipelines/' +
workflowId, input).subscribe(value => {
console.log('response for Manual Pipeline ' + value);
return value;
}, err => {
console.log(err);
});