研究员我开发了一个Rest API,我希望当一条路由不存在时,发送一个自定义消息而不是一个默认发送express.js的html。就像我搜索的那样,我找不到办法做到这一点。
我试着这样做:
app.all("*",function(req,res){
res.status(404)
res.header("Content Type","application/json")
res.end(JSON.stringify({message:"Route not found"}))
});
但它匹配并且所有已经实现的方法。我只希望我的应用程序可以处理未受影响的一个。
对于每个enndpoint,我创建一个具有以下内容的单独文件:例如。 myendpoint.js
module.exports=function(express){
var endpoint="/endpoint"
express.get(endpoint,function(req,res){
res.end("Getting data other message")
}).post(endpoint.function(req,res){
res.end("Getting data other message")
}).all(endpoint,function(req,res){
res.status(501)
res.end("You cannot "+res.method+" to "+endpoint)
})
}
我在我的主文件中使用:
var endpoint=require('myendpoint.js')
var MyEndpointController=endpoint(app)
app.all("*",function(req,res){
res.status(404)
res.header("Content Type","application/json")
res.end(JSON.stringify({message:"Route not found"}))
});
答案 0 :(得分:2)
1.Declare所有路线
2.定义不匹配的路径请求以使错误重置在结束时。
您必须在应用中进行设置。 (app.use)不在路线中。
<强> Server.js 强>
//Import require modules
var express = require('express');
var bodyParser = require('body-parser');
// define our app using express
var app = express();
// this will help us to read POST data.
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8081;
// instance of express Router
var router = express.Router();
// default route to make sure , it works.
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// test route to make sure , it works.
router.get('/test', function(req, res) {
res.json({ message: 'Testing!' });
});
// all our routes will be prefixed with /api
app.use('/api', router);
// this is default in case of unmatched routes
app.use(function(req, res) {
// Invalid request
res.json({
error: {
'name':'Error',
'status':404,
'message':'Invalid Request',
'statusCode':404,
'stack':'http://localhost:8081/'
},
message: 'Testing!'
});
});
// state the server
app.listen(port);
console.log('Server listening on port ' + port);
请注意:我的路线中有前缀'/ api'。
你会看到'{“消息”:“万岁!欢迎来到我们的api!”}'
当您尝试http://localhost:8081/api4545时 - 这不是有效路线
您会看到错误消息。
答案 1 :(得分:1)
无法发布评论(声誉太低......)但您是否在所有其他路径之后定义了此路线?
订单非常重要,您应首先定义所有路线,然后再使用此路线。
答案 2 :(得分:1)
首先,您需要定义所有现有路线,然后最后必须定义否 路线。订单非常重要
// Defining main template navigations(sample routes)
app.use('/',express.static(__dirname + "/views/index.html"));
app.use('/app',express.static(__dirname + "/views/app.html"));
app.use('/api',express.static(__dirname + "/views/api.html"));
app.use('/uploads',express.static(path.join(__dirname, 'static/uploads')));
//If no route is matched by now, it must be a 404
app.use(function(req, res, next) {
res.status(404);
res.json({status:404,title:"Not Found",msg:"Route not found"});
next();
});
答案 3 :(得分:0)
为了我的路线生命周期的安全性,我使用了这个 **/**
或 */*
,*
(星号)运算符代表所有,这是我的例子。
app.use('**/**',express.static(path.join(__dirname, './public/not-found/index.html')));