Send custom message in express.js error handling middleware - node.js

I have a REST API built with express.js and an SPA, which are communicating with each other. I have my error handling middleware as explained here. I get the correct error code on the frontend, but the message is always Request failed with error code ... How can I send custom messages via either res.status(4xx).json({message: 'My custom message to show on the SPA'}) or res.status(4xx).send('My custom message to show on the SPA')? Since I'm not rendering anything from the server, I can't add the message directly in my DOM. I have to send a json or text response.

Related

Why do we need to add .end() to a response?

Currently building a RESTful API with express on my web server, and some routes like the delete route for a document with mongoose ex. await Note.findByIdAndRemove(request.params.id) response.status(204).end() send response statuses with end()
Why do I need to add the .end()? What in these cases, and why cant one just send response.status(204)
With some responses that return json, the response.status(201).json works fine
Only certain methods with Express or the http interface will send the response. Some methods such as .status() or .append() or .cookie() only set state on the outgoing response that will be used when the response is actually sent - they don't actually send the response itself. So, when using those methods, you have to follow them with some method that actually sends the response such as .end().
In your specific example of:
response.status(204)
You can use the Express version that actually sends the response:
response.sendStatus(204)
If you choose to use .status() instead, then from the Express documentation, you have to follow it with some other method that causes the response to be sent. Here are examples from the Express documentation for .status():
res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')
Since all three of these other methods will cause the response to be sent and when the response goes out, it will pick up the previously set status.

How do I debug Axios frontend POST (React) to backend express POST? Console shows request as POST and status 200

Browser: Safari
Texteditor: VS CODE
Frontend framework: Reactjs
Backend setup: Express.js
Problem: I have an Axios post request on the front end after an onClick call event is triggered. I am unable to debug the data being sent in the body and know why it isn't getting over to the backend.
The screenshots show the code:(not the breakpoints in red. I am not sure where a good place to use debugger;
This is the code for the onClick event
This is the Backend code running on express port 8000
This is a screenshot of safari and the form being submitted. In the console is the response. As you can see it shows as post request type and status 200. None of that data gets over to the backend SQL database.
Note in the screen above that the object is rendered several times. That is because to get this code to show the results in the console I changed this function.
to this:(though according to react the above is the correct way and will only fire the function once when onclick event is triggered. The below approach does not require an onclick event.
Below is the data showed when setting a breakpoint on all requests. Note that it appears to be a GET request when it should be a POST
Note this is a POST REQUEST. This only happens when the onclick function is changed.
Any help on this matter would be greatly appreciated. I know I am close to figuring this out, however, I am still new to React and CRUD works with it.
So your backend isn't handling the request being made from the front-end. if you want to see the data, try doing this in your server. You need to handle the request your front-end is making before sending a response. The below code just destructures the request body so you don't have to write many lines of code. Once you click on the submit button, you should see that your front-end input is popping up on your back end console. You are currently trying to send an unhandled request. If you want to let's say send something to the front-end based on the request, you would do something like
res.json({nameOfThing: valueOfTheThing"}) AFTER HANDLING THE REQUEST.
app.post("/", (req, res)=>{
const {email, name, question} = req.body
console.log(`Your Email is ${email} and your name is ${name} and your ${question}`)
})
The data should appear in your console. I have actually written a blog on how to do stuff like this. Feel free to check it out. https://dev.to/gbudjeakp/how-to-connect-your-node-express-backend-with-your-react-front-end-post-610

How to send custom http response code back from spring cloud functions?

I was using Spring Cloud Functions with azure...but could not figure out how using Spring cloud function I can send a custom HTTP code back in response.... as we can do in ResponseEntityAs of now I do not see a way of doing that. let's say after validation I want to throw a 400 BAD REQUEST error in the response or add some specific parameter in the response header, how do I do that.

How can I return server side error to the client's HTML page in Express/node js?

I am creating an web app I which the user requests to create an account. The request from client's page will reach the server and query the database. Now what is the proper way of displaying User already exists error in my registeration page. In short, how can I send server side errors to my clients in Node JS?
There are some options to get what you need. The approach that I would not follow will be using the http protocol and sending a 500 response for example.
One good approach would be creating a status and a message fields in your response.
You could use code 200 for the sucessful requests and a different code for the rest. You could have a dedicated code to inform the api user that the backend coud not insert the data.
Example response:
{
code: 789
message: "User could not be inserted"
...
}

204 error code then 500 error code responses

So I have an application which needs to send data to the API which is created by our team leader using NodeJS with Express.js.
On my end I have laravel application which using VueJS for the UI. Inside the Vue JS component. I am using axios to request to the API.
axios.post('https://clearkey-api.mybluemix.net/sendcampaign', request)
.then(function(response) {
//console.log(response);
})
However, it returns 204 which means according to this https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
204 No Content
The server has fulfilled the request but does not need to return an
entity-body, and might want to return updated metainformation. The
response MAY include new or updated metainformation in the form of
entity-headers, which if present SHOULD be associated with the
requested variant.
If the client is a user agent, it SHOULD NOT change its document view
from that which caused the request to be sent. This response is
primarily intended to allow input for actions to take place without
causing a change to the user agent's active document view, although
any new or updated metainformation SHOULD be applied to the document
currently in the user agent's active view.
The 204 response MUST NOT include a message-body, and thus is always
terminated by the first empty line after the header fields.
Then next it returns 500 Internal Server Error. So in my opinion it returns this error because there is no content to be returned from the server?
Can you tell me other possible problems why it return that response?
Check if the "HTTP method" of the 204 is OPTIONS and if the method of the 500 is POST.
If both are like that, then you are seeing first a CORS pre-flight request (the OPTIONS that returns 204) and then the actual request (the POST that returns 500).
The CORS pre-flight request is a special HTTP message your browser sends to the server when the webpage and the backend are hosted at different addresses. For example, if your website is hosted at http://localhost but the backend you are trying to access is hosted at https://clearkey-api.mybluemix.net.
The reason of the 204 just means your backend endpoint is correctly setup to handle requests for /sendcampaign (you can ignore it). The reason of the 500 is because of some exception in the implementation of the function that handles that endpoint.

Resources