使用express和mysql写购物车用到的接口
时间: 2023-05-27 12:01:59 浏览: 47
这是一个简单的购物车接口示例,使用Express框架和MySQL数据库。
1. 初始化项目
首先,创建一个名为“shopping-cart”的项目文件夹,并在其中初始化一个Node.js项目:
```
mkdir shopping-cart
cd shopping-cart
npm init
```
按照提示输入项目信息和依赖项,然后安装Express和MySQL:
```
npm install express mysql --save
```
2. 创建数据库和表格
在MySQL中创建一个名为“shopping_cart”的数据库,并创建两个表格:一个用于存储购物车信息,另一个用于存储商品信息。
```
CREATE DATABASE shopping_cart;
USE shopping_cart;
CREATE TABLE cart (
id INT(11) PRIMARY KEY AUTO_INCREMENT,
product_id INT(11) NOT NULL,
quantity INT(11) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE products (
id INT(11) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
price DECIMAL(10,2) NOT NULL,
image_url VARCHAR(500),
description VARCHAR(2000)
);
```
3. 配置Express应用程序
在项目文件夹中创建一个名为“app.js”的文件,并编写以下内容:
```javascript
const express = require('express');
const mysql = require('mysql');
const app = express();
const port = 3000;
const dbConfig = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'shopping_cart',
};
const connection = mysql.createConnection(dbConfig);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send('Hello, shopping cart!');
});
app.get('/products', (req, res) => {
connection.query('SELECT * FROM products', (error, results) => {
if (error) throw error;
res.json(results);
});
});
app.listen(port, () => {
console.log(`Server listening on port ${port}.`);
});
```
这是一个最简单的Express应用程序,监听3000端口,并向根路径发送问候消息。此外,它还包含一个路由,用于从数据库中检索商品信息,并将其作为JSON响应发送。
4. 编写购物车接口
为了将商品添加到购物车,我们需要编写以下两个用于处理POST请求的路由。
```javascript
app.post('/cart/:product_id', (req, res) => {
const productId = req.params.product_id;
const quantity = req.body.quantity;
connection.query(
'INSERT INTO cart (product_id, quantity) VALUES (?, ?)',
[productId, quantity],
(error, result) => {
if (error) throw error;
res.json(result);
}
);
});
app.delete('/cart/:id', (req, res) => {
const cartItemId = req.params.id;
connection.query(
'DELETE FROM cart WHERE id = ?',
[cartItemId],
(error, result) => {
if (error) throw error;
res.json(result);
}
);
});
```
在“/cart/:product_id”路由中,我们接收请求参数(商品ID和数量),并将其插入到cart表中。在“/cart/:id”路由中,我们接收购物车项的ID,并将其从表中删除。
5. 测试接口
我们可以使用Postman等工具来测试API。使用POST请求向“http://localhost:3000/cart/1”发送以下JSON有效载荷:
```
{
"quantity": 3
}
```
这应该会将商品ID为1的商品添加到购物车中。接下来,使用DELETE请求向“http://localhost:3000/cart/1”发送,以删除购物车中的第一个项目。
6. 总结
在本教程中,我们演示了如何使用Express和MySQL创建一个简单的购物车接口。当然,这只是一个开始,您可以将其扩展为更完整的购物车应用程序。