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.
Related
I am getting blob of pdf file from other server which is on C# in node server when I am converting it to array buffer it's size is different from C# array buffer size and when I am opening it to browser it gives error "Failed to load PDF document."
This is my server side code
async post(param: any, body: any, endPoint: string, queryParams: string = '')
{
try
{
if(queryParams == '') queryParams = param.destinationSlug + '/' + param.mainBranchId;
const url = splendidAccountsEndPointsEnum.baseUrl + queryParams + endPoint;
const offset = new Date().getTimezoneOffset().toString();
const headerConfig = { headers: { 'X-Api-Key': param.apiKey, 'X-Api-Secret': param.apiSecret, 'X-App-Id': config.get<string>("splendidXAppId"), LocalDateTimeOffset: offset }}
const response = await axios.post(url, body, headerConfig)
.then(function (response: any)
{
return response?.data;
})
.catch(function (error: any)
{
console.log(error);
return error;
});
if (response?.status === 200)
{
console.log('success');
return response?.data;
}
return response;
}
catch (err)
{
console.error(err);
console.log(err);
return err;
}
}
And this is my client side
let response = this.orderService.generateInvoicePrinting(this.selectedRows)
.subscribe((res) => {
var file = new Blob([res], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
saveAs(file, "invoices.pdf");
window.open(fileURL);
this.pdfSrc = fileURL;
this.showPdf = true;
this.showSuccess('Invoices have been generated successfully.');
this.selectedRows = [];
},
error => {
this.showError('Invoices have not been generated successfully.');
});
generateInvoicePrinting(orders: any): Observable<any>
{
const url = `${environment.apiUrl}api/Order/printInvoices/pdf`;
return this.http.post(url, orders, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), observe: 'response', responseType: 'blob' }).pipe(
map(res => res.body),
);
}
I am following a course on Udemy which uses Angular 2.0 and I'm trying to build it using the latest version. My problem occurs in this function :
checkSession() {
const url = 'http://localhost:8181/checkSession';
const xToken = localStorage.getItem('xAuthToken');
const basicHeader = 'Basic ' + localStorage.getItem('credentials');
const headers = new HttpHeaders({
'x-auth-token' : JSON.stringify(xToken),
'Authorization' : basicHeader
});
console.log(url);
console.log(headers);
return this.http.get(url, {headers: headers});
because when I access it on this function:
ngOnInit() {
const xToken = JSON.stringify(localStorage.getItem('xAuthToken'));
if (xToken) {
this.loginService.checkSession().subscribe(
res => {
console.log("Good")
this.loggedIn = true;
},
error => {
console.log("error = " + error)
this.loggedIn = false;
}
);
}
it always going on the error observer throwing this error:
[object Object]
OnSubmit function:
onSubmit() {
this.loginService
.sendCredential(this.credential.username, this.credential.password)
.subscribe(
res => {
localStorage.setItem('xAuthToken', JSON.stringify(res));
this.loggedIn = true;
const encodedCredentials = btoa(this.credential.username + ':' + this.credential.password);
localStorage.setItem('credentials', encodedCredentials);
// location.reload();
},
error => {
console.log(error);
}
);
Original functions from the course:
checkSession() {
let url = "http://localhost:8181/checkSession";
let headers = new Headers ({
'x-auth-token' : localStorage.getItem('xAuthToken')
});
return this.http.get(url, {headers: headers});
ngOnInit() {
this.loginService.checkSession().subscribe(
res => {
this.loggedIn=true;
},
error => {
this.loggedIn=false;
}
);
onSubmit() {
this.loginService.sendCredential(this.credential.username, this.credential.password).subscribe(
res => {
console.log(res);
localStorage.setItem("xAuthToken", res.json().token);
this.loggedIn = true;
// location.reload();
},
error => {
console.log(error);
}
);
Because of this error, I cannot save the session. The login works like a charm, but for some reason unknown by me, the session is not saved properly.
Network tab:
The response type from server will be text instead of json which will be causing the issue. try setting the header as text
return this.http.get(url, {headers, responseType: 'text'});
Please update function as below
checkSession() {
const url = 'http://localhost:8181/checkSession';
const xToken = localStorage.getItem('xAuthToken');
const basicHeader = 'Basic ' + localStorage.getItem('credentials');
const headers = new HttpHeaders({
'x-auth-token' : JSON.stringify(xToken),
'Authorization' : basicHeader
});
console.log(url);
console.log(headers);
return this.http.get(url, {headers: headers, responseType: 'text'});
}
It looks like you are trying to stringify the variable (xToken) that you get from local storage. The problem is that the get method from local storage returns a string so when you set your HttpHeaders, it will throw an error on the JSON.stringify(xToken) line.
I'm new to JavaScript and I'm trying make a Github API Gateway for IFTTT(cause it can't modify header) with JS on Cloudflare Worker. Here's the code:
async function handleRequest(request) {
var url = new URL(request.url)
var apiUrl = 'https://api.github.com' + url.pathname
var basicHeaders = {
'User-Agent': 'cloudflare',
'Accept': 'application/vnd.github.v3+json'
}
const { headers } = request
const contentType = headers.get('content-type')
const contentTypeUsed = !(!contentType)
if (request.method == 'POST' && contentTypeUsed) {
if (contentType.includes('application/json')) {
var body = await request.json()
if ('additionHeaders' in body) {
var additionHeaders = body.additionHeaders
delete body.additionHeaders
}
var apiRequest = {
'headers': JSON.stringify(Object.assign(basicHeaders,additionHeaders)),
'body': JSON.stringify(body),
}
} else {
return new Response('Error: Content-Type must be json', {status: 403})
}
const newRequest = new Request(apiUrl, new Request(request, apiRequest))
try {
var response = await fetch(newRequest)
return response
} catch (e) {
return new Response(JSON.stringify({error: e.message}), {status: 500})
}
} else {
var apiRequest = {
'headers': JSON.stringify(basicHeaders)
}
const newRequest = new Request(apiUrl, new Request(request, apiRequest))
var response = await fetch(newRequest)
return response
}
}
addEventListener('fetch', async (event) => {
event.respondWith(handleRequest(event.request))
})
And I got this error when I tried to run it:
Uncaught (in promise)
TypeError: Incorrect type for the 'headers' field on 'RequestInitializerDict': the provided value is not of type 'variant'.
at worker.js:1:1245
at worker.js:1:1705
Uncaught (in response)
TypeError: Incorrect type for the 'headers' field on 'RequestInitializerDict': the provided value is not of type 'variant'.
This is an older version which run well but with less flexibility:
async function handleRequest(request) {
var url = new URL(request.url)
var apiUrl = 'https://api.github.com' + url.pathname
var accessToken = 'token '
var apiRequest = {
headers: {
'User-Agent': 'cloudflare',
'Accept': 'application/vnd.github.v3+json'
}
}
const { headers } = request
const contentType = headers.get('content-type')
const contentTypeUsed = !(!contentType)
if (request.method == 'POST' && contentTypeUsed) {
if (contentType.includes('application/json')) {
var body = await request.json()
if ('token' in body) {
accessToken += body.token
delete body.token
}
var apiRequest = {
headers: {
'Authorization': accessToken,
'User-Agent': 'cloudflare',
'Accept': 'application/vnd.github.v3+json'
},
body: JSON.stringify(body),
}
} else {
return new Response('Error: Content-Type must be json', {status: 403})
}
const newRequest = new Request(apiUrl, new Request(request, apiRequest))
try {
var response = await fetch(newRequest)
return response
} catch (e) {
return new Response(JSON.stringify({error: e.message}), {status: 500})
}
} else {
const newRequest = new Request(apiUrl, new Request(request, apiRequest))
var response = await fetch(newRequest)
return response
}
}
addEventListener('fetch', async (event) => {
event.respondWith(handleRequest(event.request))
})
The only difference seems to be apiRequest, but I don't know how to fix it. I tried to claim the variable with var apiRequest = new Object() first but didn't work.
Fix with this:
let apiRequest = new Object
apiRequest.headers = Object.assign(basicHeaders, additionHeaders)
apiRequest.body = JSON.stringify(body)
And the apiRequest will look like this:
{headers:{},body:"{}"}
This seems like what RequestInitializerDict want.
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 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);
});