Home > Web Front-end > JS Tutorial > Web project using Node.js to implement online voting function

Web project using Node.js to implement online voting function

PHPz
Release: 2023-11-08 11:54:20
Original
806 people have browsed it

Web project using Node.js to implement online voting function

Due to space limitations, it is impossible to explain in detail the complete Web project of Node.js to implement online voting function within 1500 words, but you can give a simple sample code first.
First, create a basic Node.js project structure, including a package.json file and an index.js file.

package.jsonThe content of the file is as follows:

{
  "name": "online-voting",
  "version": "1.0.0",
  "description": "Online voting web project",
  "main": "index.js",
  "dependencies": {
    "express": "^4.17.1"
  }
}
Copy after login

index.jsThe content of the file is as follows:

const express = require('express');
const app = express();
const port = 3000;

// 创建一个简单的投票选项
let options = {
  option1: 0,
  option2: 0,
  option3: 0,
};

// 设置投票路由
app.get('/vote/:option', (req, res) => {
  let option = req.params.option;

  if (options.hasOwnProperty(option)) {
    options[option]++;
    res.send('投票成功!');
  } else {
    res.status(400).send('无效的投票选项');
  }
});

// 设置获取投票结果路由
app.get('/results', (req, res) => {
  res.json(options);
});

app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});
Copy after login

The above sample code contains A basic Node.js web application was developed, using the Express framework to implement the online voting function. Users can access the /vote/:option route to vote for options, and access the /results route to obtain voting results.

In actual projects, the code can be further expanded, including but not limited to error handling, user identity authentication, front-end page development, etc. I hope the above simple example can help you get started with a Node.js web project that implements online voting functionality.

The above is the detailed content of Web project using Node.js to implement online voting function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template