这个教程无论node,express,koa均可以用下面方法链接,这里用koa作个参考前端
这个教程的源码地址: https://github.com/xiaqijian/...node
不少教程都没有涉及到版本,因此让不少初学者,拷贝他的代码,出现错误问题
个人版本:mysql
"dependencies": { "koa": "^2.6.2", "mysql": "^2.16.0" }
// default.js // 设置配置文件 const config = { // 启动端口 port: 3000, // 数据库配置 database: { DATABASE: 'ceshi', USERNAME: 'root', PASSWORD: '1234', PORT: '3306', HOST: 'localhost' } } module.exports = config
// mysql/index.js var mysql = require('mysql'); var config = require('../config/default.js') var pool = mysql.createPool({ host : config.database.HOST, user : config.database.USERNAME, password : config.database.PASSWORD, database : config.database.DATABASE }); class Mysql { constructor () { } query () { return new Promise((resolve, reject) => { pool.query('SELECT * from ceshidata', function (error, results, fields) { if (error) { throw error }; resolve(results) // console.log('The solution is: ', results[0].solution); }); }) } } module.exports = new Mysql()
// index.js const Koa = require('koa') const config = require('./config/default') const mysql = require('./mysql') const app = new Koa() app.use(async (ctx) => { let data = await mysql.query() ctx.body = { "code": 1, "data": data, "mesg": 'ok' } }) app.listen(config.port) console.log(`listening on port ${config.port}`)
先去数据库添加点数据git
node index.js
打开浏览器localhost:3000, 而后你就会看到如下数据,本身添加的数据查询出来了github
而后其余相关操做,能够看mysql相关API,我下次也会分享出来sql
首发于微信公众号:node前端数据库
不妨关注一下,咱们一块儿学习express
回复:100浏览器
有福利哦服务器