Angular 6 Http Request giving wrong response - javascript

I am trying to make a HTTP Post request using angular 6's HttpClientModule.
The POST request I am making is as follows:
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' })
};
httpOptions.headers = httpOptions.headers.append('Authorization', 'BasicAuth_Token');
this._http.post(url, {
s: '29'
},httpOptions).subscribe(
data => console.log('Success!',data),
error => console.error('Error!', error)
)
The Post request is successful and I am getting a response.
However I am not getting the response expected.
i.e
When I make the same POST request through AJAX:
$.ajax({
url: url,
type: 'POST',
contentType: "application/x-www-form-urlencoded",
data: { s:'29'},
success: function (data) {
console.log("code - 1000", data);
}
else {
console.log("code - 1001" , data);
}
},
error: function (response) {
console.log("Something went wrong", response);
}
});
I am getting a code - 1000 returned for the same POST data.
However I am getting a code - 1001 for POST in angular 6.
Basically, for the same POST request - though the post is successful
in both ajax and Angular 6 , I am getting different responses for the
same data.
If the post was unsuccesful , I could understand. However I am not
understanding how i am getting two different responses for the same
data i.e being sent to the API.

Related

Using axios to make a post request - node js

I'm new to node.js and i'm trying to do a post request from server side using axios But i get no response data from the request.
If i do a post request from the client side using ajax it works fine and i was just wondering am i doing something wrong?
My server side post request:
var postData ={
a: 'getMessages',
max: 50,
id: 5039
};
let postConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
}
};
axios.post('https://url.com/ajax.php', postData, postConfig).then((response) => {
console.log('response:', response.data);
}).catch((error) => {
console.log('error:', error);
});
The way i was doing post request from client side:
This worked fine but when i try to do a post request from server side there is no response data.
$.post('https://url.com/ajax.php', {
a: 'getMessages',
max: 50,
id: 5039
}, function(response) {
let data = JSON.parse(response);
console.log('data:', data);
});
Client-side, it looks like you're using jQuery $.post(), which defaults to posting JSON when sending an object like this.
I suspect that the issue is that your content type is sent to be a form. If you simply get rid of postConfig entirely, it should send it as application/json, and should properly format the request body for what you want.

Fetch API Delete Request Data Returns - null

I'm trying to send a Delete request using Fetch. I get a response status - OK, but data is null. However the request has a body with an object, but I'm unable to see it back in the data received from the request. Here is a sample code.
let myObj = {
test: test1
}
fetch(deleteUrl, {
method: 'DELETE',
headers: {
"Content-type": "application/json;charset=UTF-8"
},
body: JSON.stringify(myObj)
}).then(
response => response.json()
).then(function(data) {
console.log(data) // Here the data is always null, but I want to log the request body(myObj)
})
From my limited understanding of "fetch", you seem to looking at the response data, not the request data.

Don't want to abort HTTP request until response didn't come from backend

I am working on React web application with a Node backend in which I have implemented the functionality to upload an Excel sheet. If the Excel sheet contains fewer records then it is uploaded successfully. But if there are more than 4,000 records then HTTP request terminates but process in backend goes on. I don't want to abort the request until the response comes from the backend.
I have tried AbortController, axios. But not working for me.
front end api call
code:
const data = new FormData();
data.set("supplier_id", parseInt(this.state.productInfoFormData.productInfoSupplierId));
data.set("supplier_name", this.state.productInfoFormData.productInfoSupplierName);
data.append(
"upload_xlsx",
this.state.isNew == true
? this.state.productInfoFormData.productInfoAttachment
: ""
);
axios({
method:'POST',
url: 'http://localhost:9001/addProductInfo',
timeout:1000*300,
data,
headers: {
'Content-Type': 'application/json',
}
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});

Why I am getting two different response in browsser console and network tab

I am making an API call from my script.js file. when I send a message to chatbot It gives me two different responses in Inspect->console and Inspect->network tab.
Network tab
Console tab
script.js
fetch(`${url}/conversations/default/respond`, {
mode: 'no-cors',
method: 'POST',
// dataType:'jsonp',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
},
})
.then(function (response) {
console.log("RESPONSE",response);
if (response) {
for (let response of response) {
console.log(response.text);
createResponder(response.text);
}
} else {
createResponder("Sorry, I'm having trouble understanding you, try asking me in an other way")
}
})
.catch(function (err) {
//console.log("DIFF",err);
document.getElementById('typing').style.display = "none";
createResponder("I'm having some technical issues. Try again later :)");
});
The network tab contains all data for the request life, its start, its response status, headers, data etc etc...
On this part :
.then(function (response) {
console.log("RESPONSE",response);
if (response) {
for (let response of response) {
console.log(response.text);
createResponder(response.text);
}
} else {
createResponder("Sorry, I'm having trouble understanding you, try asking me in an other way")
}
})
you are console logging the xhr object itself, this is why your console contains "request" data and not your json data, that i guess you are expecting.
Keep on reading this and pay attention to "Response objects" section

getting json with fetch and ajax yields different responses

I have been using ajax to get back some json data and recently tried using the fetch implementation.
I am having different responses, my ajax returns a string with all my key/value pairs, while the fetch query is returning response objects which do not at all contain any of my key/value pairs. (I am requesting the exact same resource in both examples and receiving different responses)
Could anyone let me know what Im doing wrong or why this is happening?
ajax request:
$.ajax({
url: "/" + name + ".json",
dataType: "text",
success: function (data) {
console.log(data);
var json = $.parseJSON(data);
var itemArray = [];
$.each(json, function() {
itemArray.push( { value: this.id, label: this.name } );
});
//Populate the List
populateListBox(name, itemArray);
}
});
console log result: (this is the response I want to be getting using the fetch method)
[{"id":1,"name":"two on two","abbreviation":"2v2","inhouse":true,"length":50,"capacity":1,"price":"50.2","salary":"15.22","url":"http://localhost:3000/en/products/1.json"},{"id":2,"name":"threesome Lessons","abbreviation":"3SUM","inhouse":false,"length":50,"capacity":3,"price":"33.33","salary":"11.11","url":"http://localhost:3000/en/products/2.json"},{"id":3,"name":"Prod1","abbreviation":"PRR1","inhouse":true,"length":22,"capacity":2,"price":"20.0","salary":"20.0","url":"http://localhost:3000/en/products/3.json"}]
fetch request:
fetch("/" + name + ".json")
.then(function(response) {
console.log(response);
return response.json()
}).then(function(json) {
var itemArray = populateItemArray(this, json);
populateListBox(name, itemArray);
}).catch(function(ex) {
console.log('parsing failed', ex)
});
console log result: (Response an object full of other objects but seems to be only an html response without any of my requested data)
Response {}
body: (...)
bodyUsed: false
headers: Headers
ok: true
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:3000/login?locale=en"
proto: Response
I am also receiving an error in the console using the fetch method which states the following: **
SyntaxError: Unexpected token <
**
Hope someone can assist. :)
UPDATE: After closely inspecting my headers in both requests I noticed the following: My AJAX request sends through a CSRF token, as well as a cookie in the header.
All fetch requests are made as anonymous and unauthenticated (by default)
All that was needed was to add an option to the fetch request as follows:
fetch("/" + name + ".json", **{ credentials: 'same-origin' }**)
.then(function(response) {
return response.json()
}).then(function(json) {
var itemArray = populateItemArray(json);
itemArray = sortByLabel(itemArray, 'label');
populateListBox(name, itemArray);
}).catch(function(ex) {
console.log('parsing failed', ex)
});
Problem is solved! Took me long enough - the CSRF token is not needed but the cookie is definitely required as that is what allows the request to be an authenticated one. :)
fetch requires a parameter to make its requests authenticated:
credentials: 'same-origin'
Not sure, maybe change dataType: "text" to "json"?

Categories