玩具项目免不了需要后台服务,自己基于koa2+mysql运行了一个基础的server。注:全文皆为在Mac下的操作。

参考地址

To start mysql: brew services start mysql

  1. <a name="r1m5N"></a>
  2. ## mysql授权模式修改
  3. 在代码中,我么不需要密码就可以登录到mysql。但在代码中连接数据库,会报错鉴权模式已经过时,在mysql中执行如下两行:
  4. ```json
  5. mysql> alter user 'root'@'localhost' identified with mysql_native_password by '123456';
  6. mysql> flush privileges;

node项目初始化

package.json

  1. {
  2. "name": "koa-demos",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. "test": "echo \"Error: no test specified\" && exit 1"
  8. },
  9. "keywords": [],
  10. "author": "",
  11. "license": "ISC",
  12. "dependencies": {
  13. "koa": "^2.13.1",
  14. "koa-bodyparser": "^4.3.0",
  15. "koa-cors": "0.0.16",
  16. "koa-router": "^10.1.1",
  17. "mysql2": "^2.3.0",
  18. "sequelize": "^6.6.5"
  19. }
  20. }

src/app.js

  1. const { connect } = require('./database')
  2. const Koa = require('koa')
  3. const router = require('koa-router')()
  4. const app = new Koa()
  5. const bodyParser = require('koa-bodyparser');
  6. const cors = require('koa-cors')
  7. let NoteTable;
  8. app.use(bodyParser());
  9. app.use(cors())
  10. app.use(async (ctx, next) => {
  11. try {
  12. console.log( `\n${ctx.method} / ${ctx.url} \n ${JSON.stringify(ctx.request.params)} \n ${JSON.stringify(ctx.request.body)}\n` );
  13. await next();
  14. console.log(`\n${ctx.response.status}\n ${JSON.stringify(ctx.response.body)}\n`)
  15. } catch (err) {
  16. const name = err.name || 'ServerError';
  17. const message = err.original && err.original.sqlMessage ? err.original.sqlMessage : 'unknow error';
  18. ctx.status = 500
  19. ctx.body = {
  20. name,
  21. message
  22. }
  23. }
  24. });
  25. connect().then(res => {
  26. NoteTable = res;
  27. })
  28. router.post('/notes/add', async function (ctx) {
  29. ctx.body = await NoteTable.create(ctx.request.body)
  30. })
  31. router.del('/notes/:id', async function (ctx) {
  32. ctx.body = await NoteTable.destroy({
  33. where: {
  34. id: ctx.params.id
  35. }
  36. })
  37. })
  38. router.put('/notes/save', async function (ctx) {
  39. ctx.body = await NoteTable.update({
  40. content: ctx.request.body.content,
  41. category: ctx.request.body.category,
  42. }, {
  43. where: {
  44. id: ctx.request.body.id
  45. }
  46. })
  47. })
  48. router.get('/notes', async function (ctx) {
  49. ctx.body = await NoteTable.findAll()
  50. });
  51. app.use(router.routes()).use(router.allowedMethods())
  52. app.listen(4000)

src/database.js

  1. const { Sequelize } = require('sequelize')
  2. const { Note } = require('./model')
  3. const sequelize = new Sequelize('note_web', 'root', 'hello123', {
  4. host: 'localhost',
  5. dialect: 'mysql',
  6. })
  7. async function connect(forceSyncTable = false) {
  8. try {
  9. await sequelize.authenticate()
  10. console.log('Connection has been established successfully.')
  11. const NoteTable = sequelize.define('Note', Note)
  12. if (forceSyncTable) {
  13. await sequelize.sync({ force: true })
  14. console.log('All models were synchronized successfully.')
  15. }
  16. // console.log('NoteTable.create databae', NoteTable.create)
  17. return NoteTable;
  18. } catch (error) {
  19. console.error('Unable to connect to the database:', error)
  20. }
  21. }
  22. exports.connect = connect

src/model.js

  1. const { DataTypes } = require('sequelize')
  2. exports.Note = {
  3. category: {
  4. type: DataTypes.STRING,
  5. },
  6. content: {
  7. type: DataTypes.TEXT,
  8. },
  9. done: {
  10. type: DataTypes.BOOLEAN,
  11. },
  12. }

功能测试

参照上述步骤新建项目、安装依赖包、填入基础代码,即可执行 node src/app.js 进行启动。

在Postman的Collection/Import/Link 的输入框中写入如下地址,即可快速导入增删改查的接口调用。

https://www.getpostman.com/collections/efba967ee8fb2ca135fb

image.png

image.png