我将 NodeJS 与 Express 中间件一起使用,我唯一的问题是在全局函数中捕获响应(用于日志)的确切发送状态代码。
使用以下代码:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = express.Router();
app.use(bodyParser.json());
router.get('/', (req, res, next) => {
// ..... SOME LOGIC
// Suppose that the variable content is coming from the DB
if (content.length === 0)
{
// Status Code : 404
res.send(404).send("The product cannot be found");
}
// Status Code : 200
res.json(content);
});
app.use((req, res, next) => {
// Problem : Always returns 200 !
console.log(res.statusCode); …Run Code Online (Sandbox Code Playgroud)