中间件加载的顺序很重要:先加载的中间件函数也会先执行。
当您尝试访问 /custom 路由时出现 404 的原因是您在 404 错误处理程序中间件之后加载此路由。我们需要在 404 错误处理程序中间件之前保持 /custom 路由负载。这是一个解决方案:
app.js:
const createError = require('http-errors');
const express = require('express');
function createApp(customRoute) {
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use('/api', function(req, res) {
res.status(200).send({
message: 'API',
data: {
version: 'v1',
},
});
});
if (customRoute) {
app.use(customRoute.route, customRoute.controller);
}
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
res.status(err.status).send({
status: err.status,
error: err,
});
});
return app;
}
module.exports = createApp;
app.test.js:
const chai = require('chai');
const chaiHttp = require('chai-http');
const createApp = require('./app');
chai.use(chaiHttp);
chai.should();
describe('API test', function() {
it('GET/ Get root response', function(done) {
const app = createApp();
chai
.request(app)
.get('/api')
.end((err, res) => {
console.log('NORMAL', res.body);
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
res.body.should.have.property('data');
done();
});
});
it('GET/ Get custom response', function(done) {
const customRoute = {
route: '/custom',
controller: (req, res, next) => {
res.status(200).send({
customMessage: 'custom',
customData: {
version: 'v1',
},
});
},
};
const app = createApp(customRoute);
chai
.request(app)
.get('/custom')
.end((err, res) => {
console.log('CUSTOM', res.body);
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('customMessage');
res.body.should.have.property('customData');
done();
});
});
});
单元测试结果:
API test
NORMAL { message: 'API', data: { version: 'v1' } }
✓ GET/ Get root response (44ms)
CUSTOM { customMessage: 'custom', customData: { version: 'v1' } }
✓ GET/ Get custom response
2 passing (62ms)