最简单的快速路线是返回404



我在我的节点应用程序中有这样的最小设置:

server.js

/**
* Starting point for the backend
*/
'use strict'
const app = require('./app');
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
} else {
console.log("Production mode is on");
}
const port = process.env.NODE_LOCAL_PORT;
const host = process.env.HOST;
app.listen(port, () => {
console.log(`Server is listening on http://${host}:${port} `);
});

app.js

'use strict'
const express = require('express');
require('dotenv').config();
require('express-async-errors');
/* Spaceholder for routes */
const availabilityRoutes = require('./routes/availability');
const inventoryRoutes = require('./routes/inventory');
const overviewRoutes = require('./routes/overview');
const utilisationRoutes = require('./routes/utilisation');
const app= express();
app.use(express.json());
// For testing purpose
const routes = express.Router();
routes.get('/test', async(req, res, next) => {
console.log("test");
res.send("test");
});
/* Register the modules containing the routes */
app.use(process.env.PUBLIC_URL + '/api/availability', availabilityRoutes);
app.use(process.env.PUBLIC_URL + '/api/inventory', inventoryRoutes);
app.use(process.env.PUBLIC_URL + '/api/overview', overviewRoutes);
app.use(process.env.PUBLIC_URL + '/api/utilisation', utilisationRoutes);
app.use((req,res,next) => {
res.sendStatus(404);
});
module.exports = app;

/api/availability的控制器示例

const express = require('express');
const routes = express.Router();
const cors = require('cors');
const helper = require('../helper');
const allowedOrigins = ['http://localhost:3000', 'http://localhost:4000'];
//delete for prod or test env
const whitelist = {
origin: function(origin, callback) {
if(origin && allowedOrigins.indexOf(origin) == -1){
let errorMsg = 'The CORS policy for this site does not allow access from the specified Origin.';
return callback(new Error(errorMsg), false);
}
//for calls from the same host the browser do not put the origin
return callback(null, true);
}
}
//global for the entire module
const queries = helper.readJSONfile();
routes.get('/', cors(whitelist), async(req, res, next) => {
console.log("Hello");
res.send("Hello");
helper.getApiCall(req, res, queries.availability.overview);
});

依赖性:

"@influxdata/influxdb-client": "^1.14.0",
"@influxdata/influxdb-client-apis": "^1.14.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"express-async-errors": "^3.1.1",
"mysql": "^2.18.1",
"nodemon": "^2.0.9"

即使我想调用http://localhost:4000/test,我也会得到404 &;Not found &;

我不知道为什么。

您应该使用app.get()而不是routes.get()

先生,由于路由的预期代码不起作用,您使用了一个发送状态码404的中间件。这个中间件精确地:

app.use((req,res,next) => {
res.sendStatus(404);
});

除非你正确使用路由器,否则代码将无法工作。使用routes.route(/测试)。获取(....)它将开始工作。

我可能错了,我现在也在学习,如果我错了,一定要告诉我。