Console log raw data of a failed Axios get request - javascript

I would like to make an Axios get request to a private server running Flask.
In case there is an internal error in the back-end it returns an response object and an error code.:
response_object = {
"Success": False,
'error': err.message
}
return response_object, 400
The served response_object should be accessible the front-end (React.js).
axios
.get(`http://127.0.0.1:5000/data`, {
data: null,
headers: { "Content-Type": "application/json" }
})
.then(response => {
console.log(response);
})
.catch(function(error) {
console.log(error.toJSON());
});
I would expect the error to include the response object. If the URL is accessed manually in the browser the error data is visible. If there is no error in the back-end the get requests works properly.
After googling for some time I found some issues that might relate to the mentioned problem. (That is why empty data is passed in the a get request).
https://github.com/axios/axios/issues/86
https://github.com/axios/axios/issues/86
Please note that I am self taught so I might miss something obvious here. Thank you all and all the best.

I'll copy/paste my comment here so other can easily see the answer for the question
if it's a 400 status code that it's throwing (you can confirm by using the Network tab in your browser), it will fall into the catch block, the only concern is the toJSON() call... just do a simple console.log(error.message) to check if you ever get there...
I leave you a simple example so you see the catch in action
more information:
in Axios, the response text is in response.data
if you are receiving a JSON, the response.data will be automatically parsed
you do not need to pass data: null as that's the default behavior, and it's not used in a GET call (you won't pass a body in a GET call)

Related

I'm receiving a 400 bad request error: "A non-empty request body is required" from my fetch request, despite my fetch request having a body

Everytime I make a fetch request from my frontend using the following js code I receive a 400 Bad request status. The body of the response has an error object saying: "A non-empty request body is required".
When I inspect the request section on my devtools network tab it says "no payload for this request". So it looks to me it's not sending the body section of my Fetch.
It does reach the .then() method afterwards.
This is the Typescript Code:
fetch(`api/person/${person.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(person)
})
.then(() => this.router.navigate(["/"]))
this is the C# backend:
[HttpPut("{id}")]
public IActionResult Put(int id, Person person)
{
person.Id = id;
try
{
var updatedPerson = _personRepository.Update(person);
if (updatedPerson != null)
{
return Ok(updatedPerson);
}
return NotFound();
}
catch (ArgumentNullException)
{
return BadRequest();
}
}
Note that the request doesn't even reach this controller. No break points will be reached if I place any here.
This is a single page application I run from Visual Studio 2019.
It works with postman however, returning the 200 Ok status code and an object back, and reaching backend breakpoints. The request URL contains the int id and the body containing a Json object.
Okay this is not a question that has a clear answer.
Here are steps you could need to take to find out:
Make sure in your fetch request the argument person is really exist, just do console.log(person) before fetch
Make sure server accepts 'application/json' type content. Though in this case the response code should have been different.
Check the response headers, and are the origins of back end and front end are the same? What you need to see are the following:
Access-Control-Allow-Headers: *
Access-Control-Allow-Methods: PUT
Access-Control-Allow-Origin: *
Postman works as a native app on your PC and has different way of sending requests rather than your browser, sometimes this causes unclear results.
Here's a way to test what is happening.
Go to your main web site (http://localhost:5001 or whatever) in your
browser
Open up Browser Dev Tools (F12 in most browsers)
copy / paste the following fetch (code below) into your Dev console
& press
What happens? Do you get data back (printed in console)?
This will probably get you to the next step you need to take.
fetch("api/person/1")
.then(response => response.json())
.then(data => console.log(data));

Unexpected end of JSON input while consuming Response body (self-defined HTTP codes)

I receive the following error when attempting to consume the body of a Response to a successful HTTP POST request:
SyntaxError: Unexpected end of JSON input.
This is the Express.js statement I used to send the response:
res.status(204).send(response)
Express's res.send() method automatically converts JavaScript objects to JSON upon sending. Regardless, response is explicitly being transformed into JSON via JSON.stringify() in its definition statement. So I am definitely sending JSON.
--
I am consuming the request on the client as follows:
fetch(URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data) // data is defined elsewhere in the file
})
.then(res => res.json())
.then(data => console.log(data))
However, whenever I attempt to read response.body to completion (see Body), I receive the following error:
SyntaxError: Unexpected end of JSON input.
Again, I have already confirmed that the data I wish to send from server to client is in JSON format. So, something is going wrong in-transit, as I am attempting to convert something to JSON that is not actually JSON.
I suspect the resource I wish to send is being misplaced in-transit, but I am not sure how.
Brother, you are sending the wrong status code actually 204 is used for when no content is access due to some reason when everything is ok then 200 status code is used.
res.status(200).send(response);
updated answer after comment.
res.status(400).json({
code : 400,
message: "error message string"
})
The issue was that I was self-defining my status code as 204.
When HTTP status 204 is specified, only the headers of your request will be forwarded. No body content will be forwarded.
Recall that my original Express response was:
res.status(204).send(response)
By defining HTTP status 204, I ensured that the response in send(response) would be discarded.
My issue was resolved by updating my response to:
res.send(response)

Check HTTP status code in the Axios promise catch block VueJs

New to VueJS. I have the following code that retrieves data from the Controller using axios:
SubmitForm: function () {
axios({
method: 'post',
url: '/Home/SubmitedForm',
data: { "Fields": this.$data }
}).then(res => {
alert('Successfully submitted the form ');
window.close();
}).catch(err => {
if (err.response.status == 409) {
alert(`Already exists. See details: ${err}`)
}
else {
alert(`There was an error submitting your form. See details: ${err}`)
}
});
When the Controller method SubmittedForm returns 409, I want to throw a specific alert else just throw a generic alert. Based on this page: https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253 I wrote the above code. However, even thought the http status returned is 409, it still show the generic alert.
I'm pretty sure I'm missing some understanding here. Can someone please help me find out what am I doing wrong here?
Works as expected on localhost but after publishing on azurewebsites it again displays the generic error.
Maybe your API endpoint brakes CORS policy, you can't read status of such error then (despite the fact that it is visible in Networks tab in dev tools).
You can install a browser extension like "CORS everywhere" to test if it works then, but any call to API blocked by CORS will show a warning/error in the browser's console by default.
Probably because err.response.status is a string and you are comparing to number

Problem fetching external API returning JSON

I'm having issues fetching an external API who should return JSON.
The API doesn't have CORS enabled so I'm trying to use fetch with the option mode: "no-cors".
I tried to use jsonp but doesn't work at all.
So here's the piece of code:
fetch(APIURL, {
mode: "no-cors",
}).then(response => {
console.log(response)
return response.json();
}).then(data => {
console.log(data);
}).catch(err => {
console.log(err)
});
The catch statement returns this SyntaxError: "JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"
Here's the result of console.log(response)
bodyUsed: true
headers: Headers
<prototype>: HeadersPrototype { append: append(), delete: delete(), get: get(), … }
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
<prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … }
But in the network tab I can see the JSON response that I want to use so I find it weird that I can see it in there so I assume the problem is on my end. I tried validating the JSON output in a validator and it's a valid JSON.
Any Ideas?
Thanks.
Under normal circumstances, you cannot read data from a third party site due to the Same Origin Policy.
CORS allows the third party site to grant your JavaScript permission to read the data.
The no-cors setting is a means for your JavaScript to say "I do not want to do anything that requires permission from CORS". This lets you make a request to send data without being able to read the response (the benefit is that it avoids throwing an error message all over the developer console telling you that you can't read the data you aren't trying to read).
Since you need to read the data, you cannot use no-cors.
Since the site doesn't provide permission with CORS, you cannot read the data directly with client-side code.
Use a proxy.

Fetching HTTP Header Params

I'm trying to write a piece of Zap code with Run JavaScript to test the HTTP header response of a URL GET. Specifically, I'm interested in the return status and the location (basically, if it's a 302, want to know what the redirect location is).
fetch('https://www.example.com/', { method: 'GET', redirect: 'manual' })
.then(function(res) {
return res.json();
})
.then(function(json) {
var output = {status: json.status, location: json.headers.get('location')};
callback(null, output);
})
.catch(callback);
I've tried the above but (a) the test always returns rawHTML (which suggests it's following a the redirect, and (b) the output variables in the Send Outbound Zap step don't pick up anything useful (again, "Raw HTML", "ID", "Runtime Meta Logs", etc. but nothing about my headers).
You may not be able to access the Location header due to the same origin policy in most browsers: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
Furthermore, you can't stop the AJAX call from following a redirect, so that may cause you issues: How to prevent jQuery ajax from following a redirect after a post?
It looks like you are using the new built-in fetch function: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
If so, in the provided example, I dont think you need the .json() call. I got the code to run like like below, but there is no redirect at example.com so not sure exactly how your situation will handle. Also, keep in mind the same-origin policy which will likely prohibit you from accessing location header.
var callback = function(a,b){
console.log(a,b)
};
fetch('https://www.example.com/', { method: 'GET', redirect: 'manual' })
.then(function(res) {
console.log (res)
var output = {status: res.status, location: res.headers.get('location')};
callback(null, output);
})
.catch(callback);
If you control the server resource, then you could possibly do something on the server, like adding another header that won't be blocked, many sites do that adding a X-Location option that browsers don't block.
Since we're using https://github.com/bitinn/node-fetch#options under the hood - specifically the redirect: 'follow' option. It even offers the exact "set to manual to extract redirect headers".
You might try experimenting with a local Node.js REPL to figure it out. If you see it working locally but not in Zapier - just file a bug to contact#zapier.com.
I managed to get this code working:
fetch('https://www.example.com/', { method: 'GET', redirect: 'manual', follow: 0 })
.then(function(res) {
var output = {status: res.status, location: res.headers._headers.location};
callback(null, output);
})
.catch(callback);
The underlying issue appears to be (as evidenced by the output variables with "id" and "rawHTML") that the fields were somehow "stuck". When I (1) deleted the Run Javascript step, (2) reinserted a new one with the above code, the correct output fields were then returned and subsequently became available to the Send Outbound Email step.

Categories

Resources