期末作业node.js+mysql超市管理系统简易
时间: 2023-12-06 10:38:43 浏览: 114
以下是一个基于Node.js和MySQL的超市管理系统的简单示例:
1. 首先,需要安装Node.js和MySQL,并创建一个名为“supermarket”的数据库。
2. 创建一个名为“products”的表,其中包含以下列:id(自动递增的主键),name,price和quantity。
3. 在Node.js中安装mysql模块,以便能够连接到MySQL数据库。
4. 创建一个名为“app.js”的文件,并在其中编写以下代码:
```javascript
const express = require('express');
const mysql = require('mysql');
const app = express();
// 创建MySQL连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'supermarket'
});
// 连接到MySQL数据库
connection.connect((err) => {
if (err) {
console.error('Error connecting to database: ' + err.stack);
return;
}
console.log('Connected to database as id ' + connection.threadId);
});
// 获取所有产品
app.get('/products', (req, res) => {
connection.query('SELECT * FROM products', (error, results, fields) => {
if (error) throw error;
res.send(results);
});
});
// 获取单个产品
app.get('/products/:id', (req, res) => {
const id = req.params.id;
connection.query('SELECT * FROM products WHERE id = ?', [id], (error, results, fields) => {
if (error) throw error;
res.send(results[0]);
});
});
// 添加新产品
app.post('/products', (req, res) => {
const { name, price, quantity } = req.body;
connection.query('INSERT INTO products (name, price, quantity) VALUES (?, ?, ?)', [name, price, quantity], (error, results, fields) => {
if (error) throw error;
res.send('Product added successfully');
});
});
// 更新产品
app.put('/products/:id', (req, res) => {
const id = req.params.id;
const { name, price, quantity } = req.body;
connection.query('UPDATE products SET name = ?, price = ?, quantity = ? WHERE id = ?', [name, price, quantity, id], (error, results, fields) => {
if (error) throw error;
res.send('Product updated successfully');
});
});
// 删除产品
app.delete('/products/:id', (req, res) => {
const id = req.params.id;
connection.query('DELETE FROM products WHERE id = ?', [id], (error, results, fields) => {
if (error) throw error;
res.send('Product deleted successfully');
});
});
// 启动服务器
app.listen(3000, () => {
console.log('Server started on port 3000');
});
```
5. 运行“app.js”文件,启动服务器。
6. 使用Postman或类似的工具测试API端点,例如:
- GET /products:获取所有产品
- GET /products/1:获取ID为1的产品
- POST /products:添加新产品
- PUT /products/1:更新ID为1的产品
- DELETE /products/1:删除ID为1的产品
阅读全文