Node.js 如何在此处触发获取错误请求页面?
我的应用程序的工作原理如下: 对于-->Node.js 如何在此处触发获取错误请求页面?,node.js,express,Node.js,Express,我的应用程序的工作原理如下: 对于-->/anyOtherRoute-->错误页 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
/anyOtherRoute-->错误页
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/goat(不在我的数据库/对象中)-->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-like的get请求中发送get请求
/说话/除以下内容以外的任何内容:来自对象的动物,但它不起作用
错误页指的是:
app.get("*",function(req,res){
res.send("Sorry ERROR 404");
});
您需要认识到的第一件事是错误页面与任何其他页面没有什么不同。知道了这一点,您可以从示例中发回错误响应:
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);
// });
免责声明,这些代码都没有经过测试,尽管我校对过,但可能会被破坏
是的,我会测试它并让你知道。