我有这个路由器(http / api / ping.js):
var express = require('express');
var router = express.Router();
router.get('/ping', function (req, res) {
res.send("You called /api/ping");
});
module.exports = router;
此路由器嵌入此路由器(http / api / index.js):
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('You called /api');
});
router.use('/ping', require('./ping'));
module.exports = router;
我的Express.js应用程序(app.js)使用此路由器:
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('./config').logger;
// Create app
var app = express();
var server = http.createServer(app)
var io = require('socket.io')(server);
// App config
app.use(bodyParser.json());
app.use('/api', require('./http/api'));
// Display requests on console
app.use(function (req, res, next) {
logger.trace(req.method, req._parsedUrl.href);
next()
});
module.exports = {
app: app,
server: server
};
当我运行应用时,/api
会返回You called /api
,但/api/ping
会给我404.
我正在使用Node 6.9.1和Express ^ 4.14.0
答案 0 :(得分:1)
我认为订单在这种情况下很重要。尝试将/ping
置于/
获取路线之上。
router.use('/ping', require('./ping'));
router.get('/', function (req, res) {
res.send('You called /api');
});
同样在您的ping路线中,您说路线的路径为/ping
,当您将其导入其他路由器时,您也会说/ping
,路径/api/ping/ping
更改
router.get('/ping', function (req, res) {
res.send("You called /api/ping");
});
到
router.get('/', function (req, res) {
res.send("You called /api/ping");
});
答案 1 :(得分:1)
我认为你的路由在这一行上不正确
router.use('/ping', require('./ping'));
这将指向http / api / ping / ping
应该是
router.use('/', require('./ping'));