Node.js【文件系统模块、路径模块 、连接 MySQL、nodemon、操作 MySQL】(三)-全面详解(学习总结---从入门到深化)(下)

本文涉及的产品
RDS MySQL DuckDB 分析主实例,集群系列 4核8GB
RDS AI 助手,专业版
简介: Node.js【文件系统模块、路径模块 、连接 MySQL、nodemon、操作 MySQL】(三)-全面详解(学习总结---从入门到深化)

Node.js【文件系统模块、路径模块 、连接 MySQL、nodemon、操作 MySQL】(三)-全面详解(学习总结---从入门到深化)(上):https://developer.aliyun.com/article/1420290


Node.js 连接 MySQL



1、安装MySQL数据库


安装 xampp


安装包下载地址: https://sourceforge.net/projects/xampp/files/


进行下载安装


启动


新建数据库,新建表


2、安装 mysql


yarn add mysql 或者 npm install mysql


3、node.js 连接 MySQL

var mysql    = require('mysql');
//创建跟数据库的连接
var connection = mysql.createConnection({
 host   : 'localhost',
 user   : 'root',
 password : '',
 database : 'test'
});
//启动连接
connection.connect();
//执行查询
connection.query('select * from test',
function (error, results) {
 if (error) throw error;
 console.log(results);
});


Node.js nodemon



安装 nodemon


yarn add nodemon 或者 npm install nodemon --save


使用nodemon运行脚本


nodemon 脚本文件


使用package.json脚本

"scripts": {
  "start":"nodemon index.js"
}


使用 npx

npx nodemon index.js


Node.js 操作 MySQL



1、查询

connection.query('select * from test where name=?','test1', function (error, results,fields) {
 if (error) throw error;
 console.log(results,'results');
});


2、插入

connection.query('insert into test(name) values (?)','test3', function (error,results, fields) {
  if (error) throw error;
  if(results.affectedRows){
    console.log('插入成功')
 }
});


3、更新

connection.query('update test set value=? where name=?', [10,'test4'], function (error, results, fields) {
  if (error) throw error;
  if (results.affectedRows) {
    console.log('更新成功')
 }
});


4、删除

connection.query('delete from test where name=?', ['test4'], function (error, results, fields) {
  if (error) throw error;
  if (results.affectedRows) {
    console.log('删除成功')
 }
});


Node.js 应用



index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .container {
      width: 600px;
      margin: 50px auto;
   }
    table {
      width: 100%;
      text-align: center;
   }
   table thead th {
      background-color: #aaa;
   }
    table tbody td {
      background-color: #eee;
      padding: 5px
   }
    form {
      margin-bottom: 50px;
      text-align: center;
   }
    input {
      margin-bottom: 15px;
   }
    button {
      margin-left: 10px
   }
  </style>
</head>
<body>
  <div class="container">
    <!-- 新增数据的表单 -->
    <form id="form1" action="http://localhost:3030/add"  method="post">
      名称:<input type="text"  name="name"><br />
     数量:<input type="text"  name="value"><br />
      <input type="submit" value="提交" />
    </form>
    <!-- 查询数据的输入框 -->
    <input type="text" placeholder="请输入搜索的名称" id="name">
    <button onclick="onGetList()">搜索</button>
    <!-- 展示数据的列表 -->
    <table>
      <thead>
        <th>名称</th>
        <th>数量</th>
        <th>操作</th>
      </thead>
      <tbody>
      </tbody>
    </table>
  </div>
  <script>
    // 获取数据
    var onGetList = function () {
      // 获取tbody
      var tbody = document.querySelector('tbody')
      // 获取搜索框里面的内容
     const name = document.querySelector('#name').value
      // 发送获取数据的请求
      fetch('/getlist?name=' + name).then(function (data) {
        data.json().then(function (result) {
          tbody.innerHTML = null
          // 遍历返回的数据,生成每一行数据
         result.records.forEach(function (item) {
            var tr = document.createElement('tr')
            tr.innerHTML = '<td>' + item.name + '</td>' + '<td>' + item.value + '</td>'
            var td = document.createElement('td')
            var button = document.createElement('button')
            button.innerHTML = '删除'
            // 点击删除
            button.onclick = function () {
              remove(item)
           }
            td.append(button)
            tr.appendChild(td)
            tbody.appendChild(tr)
         })
       })
     })
   }
    // 删除数据
    function remove(item) {
      // 发送请求,并传递要删除数据的id
      fetch('/remove', { method: 'POST', body: JSON.stringify({ id: item.id }), headers: { 'Content-Type': 'application/json' } }).then(function (data) {
        console.log(data)
        data.json().then(function (result) {
          console.log('成功')
          onGetList()
       })
     })
   }
    window.onload = function () {
      onGetList()
   }
  </script>
</body>
</html>


mysql.js

var mysql = require('mysql');
const sqlConfig = {
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'test'
}
let connection = mysql.createConnection(sqlConfig)
const sqlFn = function (sql, arr, callback)
{
  connection.query(sql, arr, callback)
}
module.exports = sqlFn


server.js

const http=require('http')
const router=require('./router')
http.createServer(function(req,res){
  router(req,res)
}).listen('3030')


router.js

const sqlFn = require('./index')
const url = require('url')
const querystring = require('querystring')
const fs = require('fs')
module.exports = (req, res) => {
  const { pathname, query } = url.parse(req.url, true)
  console.log(req.method)
  if (req.method == 'POST') {
    let params = ''
    req.on('data', (chunk) => {
      params += chunk
   })
    req.on('end', () => {
      console.log(params)
      let postParams = querystring.parse(params)
      if (req.headers['content-type'] == 'application/json') {
        postParams = JSON.parse(params)
     }
      // 处理新增数据的请求
      if (pathname == '/add') {
        sqlFn('insert into test(id,name,value) values (null,?,?) ',[postParams.name, postParams.value], (results) => {
          if (results.affectedRows) {
           res.writeHead(200, { "Content-Type": 'application/json;charset=utf-8' })
           res.end(JSON.stringify({ code: 0, message: '操作成功' }))
         }
       })
     }
      //处理删除请求
      if (pathname == '/remove') {
        console.log(postParams)
        sqlFn('delete from test where id=? ', [postParams.id], (results) => {
          if (results.affectedRows) {
            console.log('删除成功')
            res.writeHead(200, { "Content-Type": 'application/json;charset=utf-8' })
            res.end(JSON.stringify({ code: 0, message: '操作成功' }))
         }
       })
     }
   })
 }
  if (req.method == 'GET') {
    // 处理获取数据请求
    if (pathname == '/getlist') {
      sqlFn(`select * from test where ${query.name ? 'name=?' : 'name is not null'}`, [query.name], (results) => {
        console.log(results)
        res.writeHead(200, { "Content-Type": 'application/json;charset=utf-8' })
        res.write(JSON.stringify({ code: 0, records: results }))
        res.end()
     })
   }
    //处理获取html页面请求
    if (pathname == '/index.html') {
      res.writeHead(200, { "Content-Type": 'text/html;charset=utf8' })
      fs.readFile('./index.html', (err, data) => {
        res.end(data)
     })
   }
 }
}


相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
8月前
|
JavaScript 前端开发
在Node.js中,如何合理使用模块来避免全局变量的问题?
在Node.js中,如何合理使用模块来避免全局变量的问题?
321 71
|
8月前
|
JavaScript 前端开发 开发者
Node学习笔记:HTTP模块
总的来说,Node.js的HTTP模块是一个强大的工具,可以帮助你处理HTTP协议的各种需求。无论你是想开设自己的餐厅(创建服务器),还是想去别的餐厅点菜(发出请求),HTTP模块都能满足你的需求。
292 18
|
SQL JavaScript 关系型数据库
node博客小项目:接口开发、连接mysql数据库
【10月更文挑战第14天】node博客小项目:接口开发、连接mysql数据库
|
SQL JavaScript 关系型数据库
Node.js 连接 MySQL
10月更文挑战第9天
162 0
|
JavaScript 应用服务中间件 Apache
Node.js Web 模块
10月更文挑战第7天
136 0
|
6月前
|
JavaScript Unix Linux
nvm与node.js的安装指南
通过以上步骤,你可以在各种操作系统上成功安装NVM和Node.js,从而在不同的项目中灵活切换Node.js版本。这种灵活性对于管理不同项目的环境依赖而言是非常重要的。
1573 11
|
11月前
|
弹性计算 JavaScript 前端开发
一键安装!阿里云新功能部署Nodejs环境到ECS竟然如此简单!
Node.js 是一种高效的 JavaScript 运行环境,基于 Chrome V8 引擎,支持在服务器端运行 JavaScript 代码。本文介绍如何在阿里云上一键部署 Node.js 环境,无需繁琐配置,轻松上手。前提条件包括 ECS 实例运行中且操作系统为 CentOS、Ubuntu 等。功能特点为一键安装和稳定性好,支持常用 LTS 版本。安装步骤简单:登录阿里云控制台,选择扩展程序管理页面,安装 Node.js 扩展,选择实例和版本,等待创建完成并验证安装成功。通过阿里云的公共扩展,初学者和经验丰富的开发者都能快速进入开发状态,开启高效开发之旅。
|
存储 JavaScript 搜索推荐
Node框架的安装和配置方法
安装 Node 框架是进行 Node 开发的第一步,通过正确的安装和配置,可以为后续的开发工作提供良好的基础。在安装过程中,需要仔细阅读相关文档和提示,遇到问题及时解决,以确保安装顺利完成。
965 155
|
10月前
|
资源调度 JavaScript 前端开发
前端开发必备!Node.js 18.x LTS保姆级安装教程(附国内镜像源配置)
本文详细介绍了Node.js的安装与配置流程,涵盖环境准备、版本选择(推荐LTS版v18.x)、安装步骤(路径设置、组件选择)、环境验证(命令测试、镜像加速)及常见问题解决方法。同时推荐开发工具链,如VS Code、Yarn等,并提供常用全局包安装指南,帮助开发者快速搭建高效稳定的JavaScript开发环境。内容基于官方正版软件,确保合规性与安全性。
10150 23