Getting error when I use res.json in React, it says 'JSON.parse: unexpected character at line 1 column 1 of the JSON data' - node.js

I am receiving data from my Express, Node.js backend api but when I use res.json() in React to retrieve the data I get an error. From what I observed in the res.text() response, I have the correct data I need, however it is causing an error when I use res.json();
I am looking for a way to either parse the data to allow for res.json() to work properly in react or a way to receive an array of data into react that would not cause the syntax error.
The error as it appears in the browser
The res.text() 200 response

Related

Express server Error 400 is not returning json message

I am submitting a form and if the form id already exists in the database, I am returning status 400 with a message saying that the form exists.
res.status(400).send({
status: 400,
message: "Form exists"
})
When I read the response sent back from my express server, I am getting Bad request message instead of the custom message object that I am returning. If I replace res.status(400) with res.status(200), I am getting the expected custom message object.
Weird enough, I can get the custom message object when making the server call in development environment. I get Bad Request message from my production server and I don't know why the response is different when the environment is different. I am hosting this server on IIS Manager v10
So my question is should I use status code of 200 instead of 400 in this scenario? Is there a way to return a custom message from status 400? Based on my understanding, I should use 4xx status code if there is a client input errors eg there is already an existing ID or invalid inputs.
Edit: This is my code from my React app.
axiosInstance
.post("/form/some-endpoint", formData)
.then(function () {
navigate(ROUTE_SUCCESS_PAGE);
})
.catch(function (error) {
// eslint-disable-next-line no-console
console.log(error);
alert(error.response !== undefined ? error.response.data.message : error.message);
});
This is the actual screenshot of the response from prod server (I console log it)
But in development environment, I am getting the response that I wanted.
Postman response from Prod server:
<system.webServer>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
Adding the <httpErrors existingResponse="PassThrough" /> to the server's web.config file on IIS Manager resolved my issue. Based on my understanding, bypassing the http error handler and not letting IIS to send its response is the solution that I need.
should I use status code of 200 instead of 400 in this scenario
TLDR: It depends on the usage.
If your intent is to Update a form, like using a PUT request, you should require an id and if that id does not exist, return 404.
If you are looking to Create a new form, like using a POST request, with an id or other meta data and one already exists matching the id or meta data (e.g. groupId), then 400 is fine but it could be better to use 409 stating that there is a conflict with the existing state, that being a preexisting form id or meta data. Though you don't often pass an id to a POST create request.
The full list of codes is a great place to start, but sometimes it helps to see how certain codes are used in production APIs. A good place to look is the GitHub API which shows the possible status codes for each endpoint along with a description. Take the Pulls API for example, just searching for 40 on the page gives you a lot of insight about when certain codes are used.
Comparing these statuses with your example, if you look at the PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge route, they use 409 whenever the state is not matching as they describe...
Conflict if sha was provided and pull request head did not match
This seems similar in nature to the POST request described above.
At the end of the day the crucial part is to get in the correct grouping (i.e 2xx, 4xx, etc.) after that it's more about being consistent across your API than matching the codes to exact best option. Also everyone is different and some may choose different codes for the same use case.
As far as changing the response itself on 400 status, you should be able to achieve this by setting statusMessage directly and then call res.end.
function(req, res) {
res.statusMessage = "Form exists";
res.status(400).end();
}
Also see https://stackoverflow.com/a/36507614/6943587

When i send a get request to a server on node js i get "Unexpected token in JSON at position 0"

When i started using node js everything was good and running smoothly. As soon as i tryed to connect to mongoDB the - "Unexpected token in JSON at position 0 at JSON.parse() " started to appeared every single time i was sending a get request from postman to the server. In addition, files that were already worked perfectly are no longer running and dont return any data, but as well return the same error of - "Unexpected token in JSON at position 0 at JSON.parse ()".
The error dont refers to any specific line in the code.
what may cause this error ?

Invalid and trucated data receiving while calling node API get route

While calling Node API get HTTP method data comes in truncated format, incomplete JSON.
But when calling the same api using POSTMAN getting proper response.
If is there any issue regarding NodeAPI please guide how can I solve it?

firebase Http function error

I have written a Firebase Http function.
When successful it returns status 200 with some data.
When it errors I want the client (which is using axios.post) to use a standard error handler which means showing the error.message property.
If I send an error code back with data - yes, I can access that data/message etc in error.response.data, but that isn't a pattern I can use for all errors - some errors might occur that don't give a response or data property.
So if I just want to access error.message at the client I need to be able to set that message but at the moment if I use for example:-
res.status(520).send('My custom error message')
I get:
Request failed with status 520
in the error.message, then I have to go to the error.response.data to get the actual message I want to display.
How could I do this so that I just use error.message regardless? I have tried using
res.status(x).send({error:customerror})
also tried
res.statusText = customerror
As you can see on Axios documentation, you have to use the error.response to get info from your custom message. You wouldn't be able to set the value on error.message on Axios.
If you really need to use error.message, you have to make a custom function to change it on cliente.

node.js parallel requests are crashing node app - can't render headers

Ways to replicate the problem,
A. continuously refresh the browser (cmd+r) and then the app crashes with the following message
B. run mocha test suite, inside I'm using npm module request for http request and all of them pass, however as soon as I send another request in parallel using postman while the tests are running, then the app crashes with the following message.
http.js:731
throw new Error('Can\'t render headers after they are sent to the client.'
^
Error: Can't render headers after they are sent to the client.
at ServerResponse.OutgoingMessage._renderHeaders (http.js:731:11)
at ServerResponse.writeHead (http.js:1152:20)
at puremvc.define.signInWithCredentialsSuccess (eval at include (/Library/WebServer/Documents/FICO/fico-node/app.js:3:32), <anonymous>:31:18)
the code referenced
signInWithCredentialsSuccess: function(request, response, authToken) {
response.writeHead(200, {'Content-Type': 'text/xml'})
response.end(this.mustache.render(this.successTemplate, {authToken: authToken}));
},
It's an express application combined with puremvc, so architecture is a bit different, for instance after app.get, the request and response are passed around to different decoupled modules and functions who accomplish their tasks and simply end the response by writing some output and then the process is repeated again for each subsequent request using new response/request objects passed.
I assume that I should be getting a new request and response object for each request but the error message confuses that for some reason the app.get is giving me a reference to an old response object which was already used to sent the information down to the client that's why it's refusing to modify the headers.
my node version is 0.10.32
please advise

Resources