Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Currently I am using

app.get('/prices/all', function (req, res) {
   fs.readFile( __dirname + "/" + "data.json", 'utf8', function (err, data) {
        res.set({ 'content-type': 'application/json; charset=utf-8' })
        res.end( data );
   });
}) 

which all works great however I want to send an error json response if a user attempts to use any other url e.g. /prices on its own. e.g.:

{status:"failed", error:"wrong get attempt"}

this is hosted on a sub-domain so all links for api.sitename.com/# need to be removed but /prices/all

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
136 views
Welcome To Ask or Share your Answers For Others

1 Answer

Express JS allows you to define custom error handling for unmapped routes. As such, you could create a function which would respond with the JSON you specified, when the requested resource is not present 404.

app.use(function(req, res) {
   res.send('{"status":"failed", "error":"wrong get attempt"}', 404);
});

http://expressjs.com/en/guide/error-handling.html

For further reading as to why this is the preferred way to handle 404 responses, see below:

http://www.hacksparrow.com/express-js-custom-error-pages-404-and-500.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...