nodejs创建项目并连接MySQL数据库

1、创建一个空文件夹,文件夹名为Nodejs项目名,在终端输入:npm init -y 对项目进行初始化,并在文件夹中创建一个src目录

npm init -y

2、在文件夹中创建一个bin文件夹,并在bin里面创建一个www.js作为可执行文件,文件内容如下:

// 引入http模块
const http = require('http')


// 引入回调函数
const serverHandler = require('../app')


// 设置端口号
const ROPT = 5000


// 创建服务器
const server = http.createServer(serverHandler)


//设置监听端口
server.listen(ROPT, () => {   //创建服务器时,监听5000端口
  console.log('server runing at port 5000...')
})

3、在根目录创建一个app.js作为回调函数,内容如下:

// 导入querystring模块
const querystring = require('querystring')

// 导入路由
const handleBlogRoute = require('./src/routes/blog')

// 处理POST请求
const getPostData = (req) => {
  const promise = new Promise((resolve, reject) => {
    if (req.method !== 'POST') {
      resolve({})
      return
    }
    if (req.headers['content-type'] !== 'application/json') {
      resolve({})
      return
    }
    let postData = ''
    req.on('data', (chunk) => {
      postData += chunk.toString()
    })
    req.on('end', () => {
      if (!postData) {
        resolve({})
        return
      }
      resolve(JSON.parse(postData))
    })
  })
  return promise
}

// 创建服务器
const serverHandler = (req, res) => {
  //设置请求头的,响应格式为JSON
  res.setHeader('Content-Type', 'application/json')
  //获取path请求路径
  const url = req.url
  //请求路径中包含的参数
  req.path = url.split('?')[0]

  //解析query
  req.query = querystring.parse(url.split('?')[1])

  //处理Post数据(异步)
  getPostData(req).then((posData) => {
    req.body = posData

    //设置响应数据(博客相关的路由)
    const blogDataPromise = handleBlogRoute(req, res)
    if (blogDataPromise) {
      blogDataPromise.then((blogData) => {
        res.end(JSON.stringify(blogData))
      })
      return
    }

    // 设置未找到路径的返回
    res.writeHead(404, { 'Content-type': 'text/plain' })
    res.write('404 Not Found')
    res.end()

  })

}

//导出
module.exports = serverHandler

4、安装项目运行依赖,终端输入:npm install nodemon -D,安装完毕后出现 node_modules文件夹即安装成功

npm install nodemon -D

5、安装mysql依赖,终端输入:npm install mysql

npm install mysql

6、修改package.json配置文件,修改后内容如下:

{
  "name": "nodeProject", //项目名称
  "version": "1.0.0", //项目版本
  "description": "",
  "main": "bin/www.js", //入口,这里修改为可执行文件的路径即可
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon bin/www.js" //增加执行命令,用nodemon执行可执行文件
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "nodemon": "^2.0.15"
  },
  "dependencies": {
    "mysql": "^2.18.1" //mysql模块
  }
}

7、创建请求成功或者失败的相关模型,在src目录下创建一个model目录,并在model目录中创建一个model.js来定义响应模块,model.js内容如下:

class BaseModel {
  constructor (data, message) {
    if (typeof data === 'string') {
      this.message = data
      data = null
      message = null
    }
    if (data) {
      this.data = data
    }
    if (message) {
      this.message = message
    }
  }
}

// 成功的模型
class SuccessModel extends BaseModel {
  constructor (data, message) {
    super(data, message)
    this.errno = 0
  }
}

// 失败的模型
class ErrorModel extends BaseModel {
  constructor (data, message) {
    super(data, message)
    this.errno = -1
  }
}

// 导出
module.exports = {
  SuccessModel,
  ErrorModel
}

8、连接数据库,在src目录下创建一个db目录,并在db目录中创建一个mysql.js文件用来连接数据库,mysql.js内容如下:

// 引入数据库模块
const mysql = require('mysql')
//引入数据库配置文件
const { MYSQL_CONFIG } = require('../config/db')
// 创建连接对象
const connection = mysql.createConnection(MYSQL_CONFIG)

// 开始连接
connection.connect()

// 执行aql语句
//增加
// const sql = `insert into blogs (title, content, author, createAt) values ('标题1', '内容1', '作者是傻逼', 1234598766);`
//修改
const sql = `update blogs set title='标题3' where content='内容1';`

// function execSQL (sql, callback) {
//
//   connection.query(sql, callback)
// }

function execSQL (sql) {
  const promise = new Promise((resolve, reject) => {
    connection.query(sql, (err, result) => {
      if (err) {
        reject(err)
        return
      }
      resolve(result)
    })
  })
  return promise
}

module.exports = {
  execSQL,
}

// 关闭连接
// connection.end()

9、配置mysql,在src目录中创建一个config目录,并在config目录中创建一个db.js文件用来配置mysql的相关数据,db.js内容如下:

let MYSQL_CONFIG = {}
MYSQL_CONFIG = {
  host: 'localhost', //数据库地址
  user: 'root', //数据库用户名
  password: '123456', //数据库用户密码
  port: 3306, //数据库端口号
  database: 'myblog',    //数据库名
}

//导出配置文件
module.exports = {
  MYSQL_CONFIG
}

10、对数据库进行操作,在src目录下创建一个controllers目录,并在controllers目录下创建一个blogrequest.js文件按用来对数据库进行操作,blogrequest.js内容如下:

// 导入数据库模块
const { execSQL } = require('../db/mysql')

// 博客相关的方法
// 获取博客列表
const getBlogsList = (author, keyword) => {
  let sql = `select * from blogs where 1=1 `;

  if (author) {
    sql += `and author='${author}' `;
  }

  if (keyword) {
    sql += `and title like '%${keyword}%'`;
  }

  return execSQL(sql);
}

// 获取博客详情
const getBlogDetail = (id) => {
  const sql = `select * from blogs where id='${id}'`

  return execSQL(sql).then(rows => {
    return rows[0]
  })
}

// 创建新的博客
const createNewBlog = (blogData = {}) => {
  // blogData title content author createdAt
  console.log(blogData)
  const title = blogData.title
  const content = blogData.content
  const author = blogData.author
  const createAt = Date.now()

  const sql = `
    insert into blogs (title, content, author, createAt) values ('${title}', '${content}', '${author}', ${createAt});
  `

  return execSQL(sql).then(insertedResult => {
    const id = insertedResult.insertId
    return {
      id,
    }
  })
}

// 更新博客
const updateBlog = (id, blogData = {}) => {
  // blogData title content
  const title = blogData.title
  const content = blogData.content

  const sql = `update blogs set title='${title}', content='${content}' where id=${id};`

  return execSQL(sql).then(updateResult => {
    console.log('updateResult', updateResult)
    if (updateResult.affectedRows > 0) {
      return true
    }
    return false
  })
}

// 删除博客
const deleteBlog = (id, author) => {
  const sql = `delete from blogs where id=${id} and author='${author}'`

  return execSQL(sql).then(deleteResult => {
    console.log('deleteResult', deleteResult)
    if (deleteResult.affectedRows > 0) {
      return true
    }
    return false
  })
}
// 导出
module.exports = {
  getBlogsList,
  getBlogDetail,
  createNewBlog,
  updateBlog,
  deleteBlog,
}

11、初始化路由,在src目录下创建一个routes目录,并在routes目录中创建一个blog.js文件用来处理路由,blog.js内容如下:

// 导入处理请求时返回的成功和失败模型

const { SuccessModel, ErrorModel } = require('../model/model);

// 引入对数据库处理的函数
const {
  getBlogsList,
  getBlogDetail,
  createNewBlog,
  updateBlog,
  deleteBlog,
} = require('../controllers/blogrequest');

// 处理博客相关的路由
const handleBlogRoute = (req, res) => {


  // 定义处理路由的逻辑
  const method = req.method;
  const id = req.query.id;
  const blogData = req.body;

  // 博客列表路由
  if (method === 'GET' && req.path === '/api/blog/list') {
    const author = req.query.author || '';
    const keyword = req.query.keyword || '';
    const listDataPromise = getBlogsList(author, keyword);
    return listDataPromise.then((listData) => {
      return new SuccessModel(listData);
    });
  }

  // 博客详情路由
  if (method === 'GET' && req.path === '/api/blog/detail') {
    const detailDataPromise = getBlogDetail(id);
    return detailDataPromise.then((detailData) => {
      return new SuccessModel(detailData);
    });
  }

  // 新建博客路由
  if (method === 'POST' && req.path === '/api/blog/new') {
    // const author = 'zhangsan';
    // req.body.author = author;
    const newBlogDataPromise = createNewBlog(blogData);

    return newBlogDataPromise.then((newBlogData) => {
      return new SuccessModel(newBlogData);
    });
  }

  // 更新博客路由
  if (method === 'POST' && req.path === '/api/blog/update') {
    const updatedBlogPromise = updateBlog(id, blogData);

    return updatedBlogPromise.then((updatedBlogData) => {
      if (updatedBlogData) {
        return new SuccessModel('更新博客成功!');
      } else {
        return new ErrorModel('更新博客失败...');
      }
    });
  }

  // 删除博客路由
  if (method === 'POST' && req.path === '/api/blog/delete') {
    const author = 'lisi';
    const deleteBlogPromise = deleteBlog(id, author);

    return deleteBlogPromise.then((deleteBlogData) => {
      if (deleteBlogData) {
        return new SuccessModel('删除博客成功!');
      } else {
        return new ErrorModel('删除博客失败...');
      }
    });
  }
};

module.exports = handleBlogRoute;

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值