node.js 读写数据库和中间件

查Mysql返回json

bash 复制代码
##
npm install mysql --save

不使用框架

javascript 复制代码
const http = require('http');
const mysql = require('mysql');
 
// 创建 MySQL 连接
const connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'root',
  database : 'db_devops'
});
 
// 连接到 MySQL
connection.connect();
 
// 设置 HTTP 服务器
http.createServer((req, res) => {
  if (req.method === 'GET') {
    // 执行 SQL 查询
    connection.query('SELECT * FROM student', (error, results, fields) => {
      if (error) throw error;
 
      // 将结果转换为 JSON 并发送响应
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify(results));
    });
  }
}).listen(1235, () => {
  console.log('Server is running');
});

使用express框架

javascript 复制代码
const express = require('express');
const mysql = require('mysql');
 
// 配置MySQL连接
const connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'root',
  database : 'db_devops'
});
 
// 连接MySQL
connection.connect();
 
const app = express();
const port = 3000;
 
// 查询数据的API
app.get('/api/data', (req, res) => {
  const sql = 'SELECT * FROM student';
  connection.query(sql, (error, results, fields) => {
    if (error) throw error;
    res.json(results); // 将查询结果以JSON格式返回
  });
});
 
// 启动服务器
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

读写Redis

bash 复制代码
npm install redis --save

示例:

bash 复制代码
##
相关推荐
Stream_Silver1 天前
【Node.js 安装报错解决方案:解决“A later version of Node.js is already installed”问题】
node.js
Anthony_2311 天前
基于 Vue3 + Node.js 的实时可视化监控系统实现
node.js
说给风听.2 天前
解决 Node.js 版本冲突:Windows 系统 nvm 安装与使用全指南
windows·node.js
森叶2 天前
Node.js 跨进程通信(IPC)深度进阶:从“杀人”的 kill 到真正的信号
node.js·编辑器·vim
虹科网络安全3 天前
艾体宝新闻 | NPM 生态系统陷入困境:自我传播恶意软件在大规模供应链攻击中感染了 187 个软件包
前端·npm·node.js
摇滚侠3 天前
PNPM 包管理工具和 NPM 包管理工具
vscode·npm·node.js·pnpm
心柠3 天前
webpack
前端·webpack·node.js
FreeBuf_3 天前
vm2 Node.js库曝严重沙箱逃逸漏洞(CVE-2026-22709)可导致任意代码执行
node.js
147API3 天前
改名后的24小时:npm 包抢注如何劫持开源项目供应链
前端·npm·node.js
抵梦3 天前
NPM、CNPM、PNPM:Node.js 依赖工具对比与选择
前端·npm·node.js