MaieonBrix MaieonBrix - 1 year ago 78
Node.js Question

How to redirect with expressjs for a specific status?

I'm doing a blog-app currently, and I'm struggling to find a way to redirect/send a specific status and then act accordingly.

For example, I have a function that saves data in mongodb using mongoose. Then if no errors occurred 200 status.{
if (err) throw err;
else {

I want to be able to "fetch" this status (I'm using react for my views and routes and superagent for my ajax request), and then do something, for example, If my article is successfully added then load a certain component on the page that will have an h1 saying : Great job on posting an article.

So this is the first part.

The second part is, for everything 404 or 500 errors I want express to redirect me from for example : -> and then with my react router simply render some basic 404 pages, I do not know how to do that, I'm searching a lot and couldn't find something...

And, since I lack knowledge in the HTTP basics like how server and client talk to each other, if you have any good article/books to recommend I'd like to know about.

Dan Dan
Answer Source

For first part. Depending on if you are using state or data library like flux or redux, if not, you can just have ajax response will have the HTTP status from your server. Using that, you can use setState to set a state property called something like isArticleSaveSucessful. Then simply render your success message component if that key is true.

Second part. For the better user experience which is I think what you intended, the url should still be what the user intended, ie, but the page should render a 404. Very similar to above, when the API response comes back, setState accordingly, something like articleNotFound. Then in your render function, do an if check on the the state and if it is true, then render your error component.