nodejs购物系统
时间: 2023-12-13 16:33:39 浏览: 38
以下是一个简单的nodejs购物系统的例子,它使用了express框架和MySQL数据库:
```javascript
const express = require('express');
const mysql = require('mysql');
const app = express();
// 创建数据库连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'shopping'
});
// 连接数据库
connection.connect((err) => {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected 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 } = req.body;
connection.query('INSERT INTO products (name, price) VALUES (?, ?)', [name, price], (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 } = req.body;
connection.query('UPDATE products SET name = ?, price = ? WHERE id = ?', [name, price, 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');
});
```
这个例子实现了获取商品列表、获取单个商品、添加商品、更新商品和删除商品等基本功能。你可以根据自己的需求进行修改和扩展。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)