Node.JS 如何写接口? 下面本篇文章给大家介绍一下 Node.JS 写接口的步骤. 有一定的参考价值, 有需要的朋友可以参考一下, 希望对大家有所帮助.
什么是接口?
接口 (软件类接口) 是指对协定进行定义的引用类型. 其他类型实现接口, 以保证它们支持某些操作. 接口指定必须由类提供的成员或实现它的其他接口. 与类相似, 接口可以包含方法, 属性, 索引器和事件作为成员.
可以使用 express 框架, 配合 moment(时间格式化)中间件 + cors 中间件(跨域用)+body-parser(解析表单)+MySQL 中间件写一个接口.
Express 是一个保持最小规模的灵活的 Node.JS web 应用程序开发框架, 为 Web 和移动应用程序提供一组强大的功能. node 可以使用 express 框架中的 App.get 与 App.post 等方法连接对象进行操作.
直接上代码:
- const express = require('express');
- const App = express();
- const moment = require('moment')
- // 导入 cors 模块, 该模块为跨域所用
- const cors = require('cors');
- App.use(cors());
- // 解析表单的插件
- const bodyParser = require('body-parser');
- App.use(bodyParser.urlencoded({ extended: false }))
- // 创建数据库连接对象
- const MySQL = require('mysql');
- const conn = MySQL.createConnection({
- host: '127.0.0.1',// 数据库地址
- user: 'root',// 账号
- password: 'root',// 密码
- database: 'mydb_12_9',// 库名
- multipleStatements: true // 允许执行多条语句
- })
get 表中的数据:
- App.get('/api/getlist', (req, res) => {
- const sqlStr = 'select * from zdcx'
- conn.query(sqlStr, (err, results) => {
- if (err) return res.JSON({ err_code: 1, message: '资料不存在', affextedRows: 0 })
- res.JSON({ err_code: 200, message: results, affextedRows: results.affextedRows })
- })
- })
按条件查询:
- App.get('/api/getlistdetl', (req, res) => {
- const number = req.query.number
- const sqlStr = 'select * from zdcx where number=?'
- conn.query(sqlStr, number, (err, results) => {
- if (err) return res.JSON({ err_code: 1, message: '资料不存在', affextedRows: 0 })
- res.JSON({ err_code: 200, message: results, affextedRows: results.affextedRows })
- })
- })
添加数据:
- // 添加
- App.post('/api/addcard', (req, res) => {
- const user = req.body
- user.ctime = moment().format('YYYY-MM-DD HH:mm:ss')// 格式化日期
- const sqlStr = 'insert into bank set ?'
- conn.query(sqlStr, user, (err, results) => {
- if (err) return res.JSON({ err_code: 1, message: err, affectedRows: 0 })
- res.JSON({ err_code: 0, message: '恭喜成功', affectedRows: results.affectedRows })
- })
- })
端口监听:
- App.listen(3000, () => {
- console.log('正在监听端口 3000,http://192.168.1.114:3000');
- //192.168.1.114 换成你的 ip, 本机 ip 查询用 cmd=>ipconfig
- })
运行就直接 node 你的文件名 就行了
记得安装依赖!!!!!!
记得安装依赖!!!!!!
记得安装依赖!!!!!! 建议配合 phpstudy 使用
来源: http://www.css88.com/qa/node-js/14854.html