node.js表示处理其他.get尝试 [英] node.js express handling other .get tries
问题描述
当前我正在使用
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 );
});
})
这一切都很好,但是如果用户尝试使用任何其他网址,我想发送一个错误的json响应./价格自行决定.例如:
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.:
{状态:失败",错误:尝试失败"}
它托管在一个子域中,因此需要删除api.sitename.com/#的所有链接,但/prices/all
this is hosted on a sub-domain so all links for api.sitename.com/# need to be removed but /prices/all
推荐答案
Express JS允许您为未映射的路由定义自定义错误处理.这样,您可以创建一个函数,当请求的资源不存在404时,该函数将使用您指定的JSON进行响应.
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
要进一步了解为什么这是处理404响应的首选方法,请参见以下内容:
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
这篇关于node.js表示处理其他.get尝试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!