上一次重置之前的请求数

时间:2019-01-04 17:45:29

标签: javascript node.js mongodb express mongoose

我正在创建一个API,我需要创建一个类似于api / v1 / status的路由,以查看服务器的状态,并向我返回一个JSON,其中包含对API执行的请求数量,因为该API是活动的,但是我不知道如何使用NodeJS做到这一点,有帮助吗?

我有那个statusRoutes.js:

src / routes / statusRoutes.js

// Initialize express router
let router = require('express').Router();

// Set default API response
router.get('/status', function (req, res) {
    //Here is the return number of requests
    res.json({
        status: 'API Its Working',
        message: 'Welcome to User-Register crafted with love!',
    });
});

module.exports = router

在我的api中,我有一些路线:

src / routes / userRoutes.js

const express = require('express')
const router = express.Router()

var userController = require('../controllers/userController')

// User routes
router.route('/users/')
    .get(userController.index)
    .post(userController.new);

router.route('/users/:user_id')
    .get(userController.view)
    .patch(userController.update)
    .put(userController.update)
    .delete(userController.delete)

// Export userRoute
module.exports = router

我的index.js是这样配置的:

src / index.js

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const expressValidator = require('express-validator');

const app = express();
const http = require('http').Server(app);

// Import routes
const statusRoutes = require("./routes/statusRoutes");
const userRoutes = require("./routes/userRoutes");

// Configure bodyparser to handle post requests
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(expressValidator());

const dbName = process.env.NODE_ENV === 'dev' ? 'database-test' : 'database';
// Connect to Mongoose and set connection variable
const url = `mongodb://${process.env.MONGO_INITDB_ROOT_USERNAME}:${process.env.MONGO_INITDB_ROOT_PASSWORD}@${dbName}:27017/?authMechanism=SCRAM-SHA-1&authSource=admin`;
mongoose.set('useCreateIndex', true);
mongoose.connect(url);

var db = mongoose.connection;
// Setup server port
var port = process.env.PORT || 8080;

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", 'GET,PUT,POST,DELETE,PATCH');
    res.header("Access-Control-Allow-Headers", "Content-Type");
    next();
});


// Send message for default URL
app.get('/', (req, res) => res.send('User-Register is Working!!'));

// Use Api routes in the App
app.use('/api/v1', statusRoutes);
app.use('/api/v1', userRoutes);

// Launch app to listen to specified port
app.listen(port, function () {
    console.log("Running User-Register on port " + port);
    app.emit('APP_STARTED');
});

module.exports = app

1 个答案:

答案 0 :(得分:7)

您可以创建在每个路由之前运行的中间件:

var count = 0;
app.use('*', (req, res, next) => { count++; next(); });

很显然,count将在服务器关闭或崩溃时重置,因此,您还可以考虑添加数据库之类的永久性存储。像Redis这样的数据库在存储快速变化的数据方面令人难以置信。

而且,正如瑞安(Ryan)在评论中指出的那样,该方法无法扩展为多次食用。在这种情况下,唯一的选择就是使用所有服务器都通用的外部存储。