Node.js 如何实现访问者计数器

Node.js 如何实现访问者计数器

我们将使用express和mongoose在nodeJS中实现访问者计数器。使用mongoose将计数存储在MongoDB数据库中的好处是,在重新启动服务器时不会丢失计数。每当浏览器获取该页面时,访问者计数将增加1。让我们逐步进行。

步骤1: 创建一个名为”app.js”的文件,并使用npm初始化您的项目。

npm init

步骤2: 使用npm安装express和mongoose

npm install express
npm install mongoose

Express包将帮助我们创建服务器和定义GET请求的路由。 Mongoose是一个用于MongoDB和NodeJS的对象数据建模库,它将帮助我们与我们的MongoDB数据库进行通信。

项目结构: 项目结构将如下所示:

Node.js 如何实现访问者计数器

步骤3: 开始编写“ app.js ”文件。

  1. 首先require express和mongoose
  2. 创建与本地MongoDB数据库的连接
  3. 定义mongoose模式以存储记录。它有两个字段,一个是“ name ”,为字符串数据类型,另一个是“ count ”,为数值数据类型。
  4. 从模式创建mongoose模型
  5. 定义根 GET 请求并使应用程序监听本地端口。

GET请求有一种特殊情况,即应用程序首次被访问时。对于这种情况,我们需要创建默认记录,访客计数为1(one)。其他时间只需将其值递增一次。

我们使用mongoose的 findOne() 函数,它接受一个参数作为搜索条件。它返回与条件匹配的第一条记录。如果没有匹配的记录,则返回 null 值。现在让我们来看看“ app.js ”文件的完整代码。

app.js

// Requiring express to handle routing 
const express = require('express') 
  
// Creating app  
const app = express() 
  
// Requiring mongoose to handle mongoDB Database 
const mongoose = require('mongoose') 
  
// Connecting to local MongoDB 
mongoose.connect("mongodb://localhost:27017/visitCounterDB", { 
    useNewUrlParser: true
}); 
  
// Creating visitor Schema to hold the 
// count of visitors 
const visitorSchema = new mongoose.Schema({ 
    name: String, 
    count: Number 
}) 
  
// Creating Visitor Table in visitCounterDB 
const Visitor = mongoose.model("Visitor",visitorSchema) 
  
// Get request to app root 
app.get('/', async function(req,res){ 
      
    // Storing the records from the Visitor table 
    let visitors = await Visitor.findOne({name: 'localhost'}) 
  
    // If the app is being visited first 
    // time, so no records 
    if(visitors == null) { 
          
        // Creating a new default record 
        const beginCount = new Visitor({ 
            name : 'localhost', 
            count : 1 
        }) 
  
        // Saving in the database 
        beginCount.save() 
  
        // Sending the count of visitor to the browser 
        res.send(`<h2>Counter: `+1+'</h2>') 
  
        // Logging when the app is visited first time 
        console.log("First visitor arrived") 
    } 
    else{ 
          
        // Incrementing the count of visitor by 1 
        visitors.count += 1; 
  
        // Saving to the database 
        visitors.save() 
  
        // Sending the count of visitor to the browser 
        res.send(`<h2>Counter: `+visitors.count+'</h2>') 
  
        // Logging the visitor count in the console 
        console.log("visitor arrived: ",visitors.count) 
    } 
}) 
  
// Creating server to listen at localhost 3000 
app.listen(3000,function(req,res){ 
  
    // Logging when the server has started 
    console.log("listening to server 3000") 
})

步骤4: 现在运行应用程序

node app.js

输出: 现在通过访问 http://localhost:3000 在你的浏览器中加载应用程序

Node.js 如何实现访问者计数器

关闭服务器并重新启动后,当我们访问根页面时,发现访客数目 保持不变 并增加了一。我们也会将所有这些步骤记录到控制台上以进行验证和理解输出。

Node.js 如何实现访问者计数器

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程