MaieonBrix MaieonBrix - 12 days ago 5
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.

newArticle.save(function(err){
if (err) throw err;
else {
res.sendStatus(200);
}
});


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 : myblog.com -> myblog.com/something 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

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, blog.com/bad-article-name 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.

Comments