我在回调响应函数中定义了一条路由。但是当我访问此路由时,如果我在函数之外定义了此路由,则express js会给出404找不到错误,而不是它起作用。我的旧项目可以按照这种逻辑正常工作,但是新项目却无法正常工作。
IDE:Webstorm 2020.1.1
以下是我的代码
www.js(启动脚本)
#!/usr/bin/env node
/**
* Module dependencies.
*/
let app = require('../src/app');
let debug = require('debug')('whatsapp-bsp:server');
let http = require('http');
/**
* Get port from environment and store in Express.
*/
let port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
let server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
let port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
let bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
let addr = server.address();
let bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
app.js
let app = express();
let cookieParser = require('cookie-parser');
let logger = require('morgan');
const config = require('../config');
const port = config.PORT;
const PubSub = require('./pubsub');
const amqp = require('./amqp');
app.use("*", function (req, res, next) {
console.log(req.method + " " + req.originalUrl);
next();
});
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('cors')(config.cors));
const indexRouter = require('./routes');
const myRouter = require('./routes/myRouter')
amqp.createChannel().then(async channel => {
const pubsub = new PubSub(channel);
app.use('/webhook', myRouter(pubsub)); // This Route Does not work
});
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
console.log("I'm listening on " + port);
module.exports = app;
myRouter.js
const express = require('express');
const router = express.Router();
module.exports = (pubsub) => {
router.post('/:value', function (req, res) {
if (!req.body) {
res.json({ data: { success: false, error: 'Request Body Required!' } })
}
pubsub.publish({ ...req.body, extension: req.params.value }, req.params.value)
.catch(e => {
console.log('Error Publishing Messaging!!', e);
res.json({ data: { success: false, error: 'Error publishing!' } })
})
res.json({ data: { success: true, message: 'Published Successfully!' } })
});
return router;
}