我的应用程序的工作方式如下:
对于-> /anyOtherRoute --->error page
但是我要执行以下操作:for-> /speak/goat(which is not in my database/objects) -->error page
var animals={
pig: "Oink",
cow: "Moo",
dog: "Woof"
};
app.get("/speak/:animal",function(req,res){
//HERE IT WILL CHECK IF THE ANIMAL IS AN OBJECT
//if not get request to the error page should be sent
var animal=req.params.animal;
var sound=animals[animal];
res.send("The "+animal+" says "+sound);
});
我尝试在/ speak /:animal的get请求中发送get请求 / speak /除了对象上的:animal以外的任何东西,但是没有用。
错误页面指的是:
app.get("*",function(req,res){
res.send("Sorry ERROR 404");
});
答案 0 :(得分:2)
您需要识别的第一件事是错误页面与其他页面没有什么不同。知道了这一点,您可以从示例中发送回错误响应:
var animals = {
pig: "Oink",
cow: "Moo",
dog: "Woof",
human: "Hello"
};
app.get("/speak/:animal", function(req, res) {
var animal = req.params.animal;
var sound = animals[animal];
if (!sound) { // Check if sound got set to a truthy value
res.status(404).send("Sorry ERROR 404"); // Note call to `status` to send actual 404
return; // Stop function execution without trying to send sound
}
// We will only get here if we didn't `return` earlier
res.send("The "+animal+" says "+sound);
});
app.get("*", function(req, res) {
res.status(404).send("Sorry ERROR 404");
});
现在,我们不想在多个地方重复该错误消息。如果我们添加更多类似的路线,然后决定更改错误页面的外观,该怎么办?我们将不得不在许多不同的地方进行更改。为了解决这个问题,我们可以添加一个函数,该函数可以为我们发送错误响应,以便仅在一个位置定义消息。
var animals = {
pig: "Oink",
cow: "Moo",
dog: "Woof",
human: "Hello"
};
function notFound(req, res) {
res.status(404).send("Sorry ERROR 404");
}
app.get("/speak/:animal", function(req, res) {
var animal = req.params.animal;
var sound = animals[animal];
if (!sound) { // Check if sound got set to a truthy value
notFound(req, res); // send the error message
return; // Stop function execution without trying to send sound
}
// We will only get here if we didn't `return` earlier
res.send("The "+animal+" says "+sound);
});
app.get("*", notFound);
// The line above is a more concise way of writing:
// app.get("*", function(req, res) {
// notFound(req, res);
// });
免责声明,此代码均未经过测试,尽管我对其进行了校对,但可能会损坏。