Node.js及mysql的安装,建立页面,javascript对mySQL数据库的操作过程

 具体动态效果看视频

node.js连接MySQL数据库操作

第一部分;配置服务器环境

 Nods.js, NPM,CNPM,mysql2,express的安装

前往 Node.js 官方网站(https://nodejs.org/)下载并安装最新的稳定版本,确定配置好path环境变量,其他服务器解释语言环境安装也用同样的方法,确保能定位到主程序目录。

敲入cmd命令>查看node版本

[第1步]cmd命令> npm config set registry http://mirrors.cloud.tencent.com/npm/

[解释]:npm config set registry  https://registry.npmjs.org     //官方镜像源

国内有多个 npm 镜像源,常用的包括:

淘宝镜像:

搜索地址:http://npm.taobao.org/

registry 地址:http://registry.npm.taobao.org/

淘宝新镜像源:https://registry.npmmirror.com/

cnpmjs 镜像:

搜索地址:npmmirror 镜像站

registry 地址:http://r.cnpmjs.org/

【可以用】腾讯云镜像源:http://mirrors.cloud.tencent.com/npm/

华为云镜像源:https://mirrors.huaweicloud.com/repository/npm/

阿里云镜像源:https://registry.npm.alibaba-inc.com/

中国科技大学镜像:npm | Home

[第2步]cmd命令>安装npm, npm install -g npm@latest  //选择最新的npm安装,

安装成功提示如下:

[解释]:npm cache clean --force 命令来清除缓存

npm install -g npm@latest :这将把 npm 升级到最新版本。--

dos命令>npm -v查看npm的版本

查看提示如下:

npm安装cnpm

[第3步]cmd命令> npm install -g cnpm

安装成功提示如下:

dos命令>cnpm -v 查看cnpm版本

查看提示如下:

[第4步]cmd命令>cnpm install mysql

安装node的MySQL插件

     cnpm install mysql --save

    cnpm install -g mysql 

安装成功提示如下:

[第5步]cmd命令>安装 MySQL2 驱动:

cmd命令>cnpm install mysql2 

安装成功提示如下:

[第6步]cmd命令>安装express

cmd命令>npm install express

这里显示需要安装 express和mysql2,输入命令npm install express和npm install mysql2

安装成功提示如下:

MySQL的安装与配置

个人喜欢DOS命令手动安装mySQL,用这个绿色版本mysql-8.3.0-winx64

把x盘:\mysql-8.3.0-winx64\bin目录添加path环境变量中

      安装MySQL服务: mysqld --install mysql

       移除MySQL服务: mysqld --remove mysq

      启动MySQL服务:  net start mysql

初始化  mysqld --initialize --console

登录MySQL      mysql -u root -p

初始登录,设置密码   set password for username @localhost = password('root');

单独安装MySQLserver-8.4.0+ 版本安装,进入MySQL官网MySQL,具体看教程MySql 安装与使用(非常详细)_mysql安装-CSDN博客

或者,安装wamp_服务器(apache_mysql_php服务器)

或者,xampp_服务器(Apache_MySQL_PHP_PERL)

MySQL图形界面管理工具安装 navicat_for_mysql,datagrip-2023,mysql-connector-j-8.3.0

Web SQL(Win_edge的浏览器数据库)也可以了解下。

第二部分:创建网站文件

[第7步]创建server.js的服务文件,代码如下,根据实际情况自己替换 MySQL用户名、MySQL密码、MySQL数据库名,主意文中仍然有四处需要更换的"MySQL数据库表格名"

const express = require('express');
const mysql = require('mysql2');
const path = require('path');
 
const app = express();
 
// 创建数据库连接配置
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'MySQL用户名',
  password: 'MySQL密码',
  database: 'MySQL数据库名'
});
 
// 执行添加自增主键的操作
connection.query('ALTER TABLE MySQL数据库表格名 ADD id INT PRIMARY KEY AUTO_INCREMENT FIRST', (err) => {
  if (err) {
    console.error('添加自增主键出错:', err);
    return;
  }
  console.log('自增主键添加成功');
});
 
// 处理跨域
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});
 
// 解析请求体的中间件
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
 
app.get('/getData', (req, res) => {
  console.log('开始执行数据库查询');
  connection.query('SELECT * FROM MySQL数据库表格名', (err, results) => {
    if (err) {
      console.error('数据库查询出错:', err);
      res.status(500).send('数据库查询错误');
      return;
    }
    console.log('查询成功,结果:', results);
    res.send(results);
  });
});
 
app.post('/writeData', (req, res) => {
  console.log('请求方法:', req.method);
  console.log('请求头:', req.headers);
  console.log('原始请求体数据:', req.rawBody);
  //console.log('接收到的请求体数据:', req.body); 
  const { name, age, education, experience } = req.body;
 
  console.log('接收到的姓名:', name);
  console.log('接收到的年龄:', age);
  console.log('接收到的学历:', education);
  console.log('接收到的工作经验:', experience);
 
  connection.query('INSERT INTO MySQL数据库表格名 (姓名, 年龄, 学历, 工作经验) VALUES (?,?,?,?)', [name, age, education, experience], (err, results) => {
    if (err) {
      console.error('数据写入出错:', err);
      res.status(500).send('数据写入错误');
      return;
    }
    console.log('数据写入成功');
    res.send('数据写入成功');
  });
});
 
app.delete('/deleteData', (req, res) => {
  const id = req.query.id;  // 获取要删除的行的 id
 
  // 在此处执行数据库删除操作
  connection.query('DELETE FROM MySQL数据库表格名 WHERE id =?', [id], (err, results) => {
    if (err) {
      console.error('删除数据出错:', err);
      res.status(500).send('删除数据错误');
      return;
    }
    console.log('数据删除成功');
    res.send('数据删除成功');
  });
});
 
// 处理静态文件请求
app.use(express.static(path.join(__dirname)));
//app.use(express.static(path.join(__dirname, '/data')));
 
app.listen(3000, () => {
  console.log('服务器运行在 3000 端口');
});

[第8步]创建代码插入网页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>数据表格</title>
</head>
 
<body>
  <form id="dataForm">
  <table id="dataTable" border="1" align="center">
    <tr>
      <th width=80>姓名</th>
      <th width=80>年龄</th>
      <th width=80>学历</th>
      <th width=120>工作经验</th>
    </tr>
	<tr>
      <th width=80 ><input type="text" id="name" size="10"/></th>
      <th width=80><input type="number" id="age" size="10"/></th>
      <th width=80><input type="text" id="education" size="10" /></th>
      <th width=120><input type="number" id="experience" size="10"/></th>
    </tr>
	<tr>
      <th colspan="4" align= ><button type="submit">提交</button></th>
    </tr>  
  </table>  
</form>
<script>
	const form = document.getElementById('dataForm');
	form.addEventListener('submit', (e) => {
	  e.preventDefault();		
	  const name = document.getElementById('name').value;	  
	  const age = document.getElementById('age').value;	  
	  const education = document.getElementById('education').value;	  
	  const experience = document.getElementById('experience').value;
	  
 console.log('即将发送的请求体数据:', JSON.stringify({ 
    name: name, 
    age: age, 
    education: education, 
    experience: experience 
  }));
	  fetch('http://localhost:3000/writeData', {
		method: 'POST',
		headers: {
		  'Content-Type': 'application/json'
		},
		body: JSON.stringify({ 
		  name: name, 
		  age: age, 
		  education: education, 
		  experience: experience 
		})
	  })
	.then(response => {
		if (response.ok) {
		  alert('数据提交成功!');
		} else {
		  alert('数据提交失败!');
		}
	  })
	.catch(error => {
		console.error('提交数据出错:', error);
	  });
	});
  </script>
<p align="center"><a href="freeback.html">进入查询页面</a></p>
</body>
 
</html>

[第9步]创建代码查询网页 freeback.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>
    #dataTable td {
      text-align: center;
    }
    #dataTable td u:hover {
      color: red;
    }
  </style>
</head>
 
<body>
<div id="tableContainer">
  <table id="dataTable" border="1" align="center">
    <tr>
      <th width=80>姓名</th>
      <th width=80>年龄</th>
      <th width=80>学历</th>
      <th width=120>工作经验</th>
	   <th width=120>操作</th>
    </tr>
  </table>
</div>
  <script>
    fetch('http://localhost:3000/getData')
   .then(response => response.json())
   .then(data => {
        const table = document.getElementById('dataTable');
        data.forEach(item => {
          const row = table.insertRow();
          const nameCell = row.insertCell(0);
          const ageCell = row.insertCell(1);
          const educationCell = row.insertCell(2);
          const experienceCell = row.insertCell(3);		  
 		  const deleteCell = row.insertCell(4); // 新增"删除"单元格
			
          nameCell.innerHTML = item.姓名;
          ageCell.innerHTML = item.年龄;
          educationCell.innerHTML = item.学历;
          experienceCell.innerHTML = item.工作经验;			
		  deleteCell.innerHTML = '<u>删除</u>'; // 单元格内添加"删除"文本
			
		  // 为"删除"单元格添加点击事件
      	deleteCell.addEventListener('click', function() {
        // 发送请求到后端删除数据库中的对应行
        fetch(`http://localhost:3000/deleteData?id=${item.id}`, {  // 假设您的数据库表中有一个名为 id 的主键,您需要根据实际情况修改
          method: 'DELETE'
        })
		.then(response => {
          if (response.ok) {
            table.deleteRow(row.rowIndex);
          } else {
            console.error('删除失败');
          }
        })
       .catch(error => {
          console.error('删除出错:', error);
        });
		});				
        });
      })
   .catch(error => {
        console.error('获取数据出错:', error);
        alert('获取数据出错,请检查!');
      });
  </script>
<p align="center"><a href="index.html">返回插入页面</a></p>
</body>
 
</html>

[第9步]启动服务端  node server.js

在浏览器中输入localhost:3000便可查看这个index.html的主页

具体动态效果看b站视频JavaScript对MySQL数据库的添加查看删除操作的页面及配置过程_哔哩哔哩_bilibili

第三部分;VUE,H5自动编译(待续)

[第9步] 安装vue的脚手架 到项目

cnpm install -g @vue/cli

[第10步] 开始一个新的vue项目

vue create <project-name>

[第8步]安装h5网站编辑工具 HBuilderX

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
安装和配置npm和cnpm,可以按照以下步骤进行操作。 1. 首先,对于npm的安装,可以使用以下命令来安装npm: npm install -g cnpm --registry=http://registry.npm.taobao.org 或者 npm install -g cnpm --registry=https://registry.npm.taobao.org 2. 对于cnpm的安装,可以使用以下命令来安装cnpm: sudo npm install -g cnpm 3. 安装完成后,可以通过以下命令来验证npm和cnpm是否安装成功: npm -v cnpm -v 4. 配置npm的镜像源,可以选择使用淘宝镜像源,可以使用以下命令进行配置: npm config set registry https://registry.npm.taobao.org 5. 配置cnpm的镜像源,可以使用以下命令进行配置: cnpm config set registry https://registry.npm.taobao.org 通过以上步骤,你就可以成功安装和配置npm和cnpm。npm是Node.js 的包管理工具,而cnpm是通过淘宝镜像源加快安装软件的速度的一个工具。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [npm和cnpm(windows)安装步骤](https://blog.csdn.net/qq_40323256/article/details/100825982)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [npm && cnpm安装与配置](https://blog.csdn.net/Shangguanyaqing/article/details/107923357)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [关于Mac下安装nodejs、npm和cnpm的教程](https://download.csdn.net/download/weixin_38611508/14875586)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值