Node实操--写一个真正的端口
1. 目标
基于nodejs 用express + mysql 包 写接口,实现学生数据添加和查询。
2. 要求
2.1 接口1
添加学生数据
url: localhost:3000/api/student
method: post
参数格式:普通键值对
-
name: 字符串 age: 数值
测试:postman来测试
2.2 接口2
获取所有的学生数据
url: localhost:3000/api/student
method: get
参数:无
测试:postman来测试
3. 思路
- 创建项目serverAPI
- npm init --yes
- 安装包: npm i express mysql
- restful风格
4. 实现添加
封装 sql.js文件
// 1. 加载mysql
const mysql = require(mysql);
// 2. 创建连接对象
const connection = mysql.createConnection({
// 对象的属性名字不能改变
host: localhost,
port: 3306,
user: root,
password: root,
database: node136
});
// 3. 连接到MySQL服务器
connection.connect((err) => {
// 如果有错误对象,表示连接失败
if (err) return console.log(数据库连接失败)
// 没有错误对象提示连接成功
console.log(mysql数据库连接成功)
})
module.exports = connection
sql.js文件引入
参考代码--添加数据
const express = require(express)
const app = express()
app.use(express.urlencoded())
// 引入封装好的sql.js
const connection = require(./tools/sql.js)
// post请求
app.post(/api/student, (req, res) => {
console.log(req.body)
// 1. 结构赋值 接收普通键值对参数
const { name, age } = req.body
// 2.添加到数据库中
const sql = `insert into student(name, age) values(${name},${age})`
console.log(要执行的sql, sql)
// connection.query(sql语句,(err, data)=>{}
connection.query(sql, (err, data) => {
if (err) {
console.log(err)
// 返回
res.json({ mag: 添加失败, code: 0 })
} else {
console.log(data)
// 返回
res.json({ mag: 添加成功, code: 1 })
}
})
})
参考代码--查询信息
// get请求
app.get(/api/student, (req, res) => {
// 查询数据库student表中的所有数据
const sql = `select * from student `
connection.query(sql, (err, data) => {
if (err) {
console.log(err)
// 返回
res.json({ mag: 添加失败, code: 0 })
} else {
console.log(data)
// 返回
res.json({ mag: 添加成功, code: 1, result: data })
}
})
})
// 接口
app.listen(3000, () => {
console.log(接口服务器启动,3000...)
})
数据库信息
5.postman测试
添加数据:
刷新数据库 :数据添加成功
查询数据
