firebase Http function error - node.js

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.

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

VueJS axios.get returns Error: Request failed with status code 404

I've been debugging this code for a while, without much luck:
async getEvents() {
try {
let response = await axios.get("http://localhost:8000/events/");
console.log(response);
return response.data;
} catch (error) {
console.error(error);
}
}
The complete code sample is from: https://auth0.com/blog/how-to-make-secure-http-requests-with-vue-and-express/
I receive an error when visiting the site that calls the API endpoint:
Error: Request failed with status code 404
at createAxiosError (utils.js?c786:148)
at Object.settle (utils.js?c786:127)
at handleRequest (handle_request.js?da0c:126)
at eval (index.js?94db:26)
at new Promise (<anonymous>)
at MockAdapter.eval (index.js?94db:25)
at dispatchRequest (dispatchRequest.js?5270:52)
If I just copy the url (http://localhost:8000/events/) in the browser I receive the correct data. I have tried with and without trailing slashes.
Am I misunderstanding the error message, and should I look elsewhere?
In computer network communications, the error 404 indicates that the browser was able to communicate with a given server, but the server could not find what was requested, in other words, the request url did not exist. So you want to double-check that.
Solution: Go to the network tab, click on the error request, inside the Headers, you can see the actual request url which has been sent to the server.
A 404 usually indicates that the resources was not found. Have you added any previous setup to your Axios instances? like the baseURL?
Most of the time the BaseURL is set to on an Axios instance that can cause confusion and issues.
I Had the same issue, then just added in my catch(vuex) error.response

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

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

Browser not showing Internal Server Error HTML Page with status 500

I've two components in my application. A frontend which is built on Angular and backend built using express. I'm using the Nest.js framework in the backend.
I have an http-exception.filter.ts file which takes care of any thrown exception. So far, I've been handling Internal Server Error in the application this way.
if(exception.getStatus() === 500) {
response
.status(500)
.json({
status: '500',
code: 'INTERNAL_SERVER_ERROR',
message: 'Internal Server Error'
});
}
But, now an HTML page has been designed showing Internal Server Error message. All I need to do to render that page is to hit the URL /ui/internal-server-error. So, I tried to that using the code below.
response
.status(500)
.redirect('/ui/internal-server-error');
The page loads when a case of internal server error occurs, but the problem is I'm not getting 500 status when I'm reading the network logs in the browser. Instead, I'm getting 304 Not modified status.
Could anyone please point me in the right direction? I want to show the error page along with status code 500 and the UI page needs to come from Frontend only as I've no access over it.
When redirect is called, it sets the status, so the 500 is replaced.
From the express docs (relevant as NestJS uses Express by default):
Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code . If not specified, status defaults to “302 “Found”.
res.redirect('/foo/bar')
res.redirect('http://example.com')
res.redirect(301, 'http://example.com')
res.redirect('../login')
Add the desired status as an argument to redirect.

Why Send API Status Codes?

I'm building my first API with node.js and was wondering do I need to ensure that a status code is send with every response or is it ok to simply use a boolean.
Is it critical for security or something?
So code wise:
return res.status(403).send({ message: 'No token provided.' });
Versus
return res.json({ success: false, message: 'No token provided.' });
Thanks.
HTTP status codes are understood by every HTTP client, be it cURL, a browser, a web proxy or a library for a programming language.
If you use just 200 OK status code, then a client that doesn't know your application won't be able to tell success from error. In case of proxies this may even cause caching problems.
On top of it, using codes properly makes it easier for the user to write a client. For instance I could use response.raise_for_status in Python Requests or $.get().then(onSuccess, onError) in jQuery.

Resources