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 复制代码
##
相关推荐
meilindehuzi_a11 小时前
从零开始:用原生 Node.js 徒手拆解 RAG 与向量检索底层原理
node.js·rag
炒毛豆11 小时前
ai全栈-node.js相关的学习之路(草稿版)
学习·node.js
meilindehuzi_a13 小时前
解密 MCP 协议:如何用 Node.js 从零手写一个本地文件读取 MCP 服务器
运维·服务器·node.js
hoLzwEge3 天前
pnpm vs npm:新一代包管理器的范式革命
前端框架·node.js
麻辣凉茶3 天前
给阿嬤一封来自云端的信(上)
前端·node.js
codingWhat4 天前
能效平台设计方案(打通gitlab和飞书)
后端·node.js·koa
见过夏天6 天前
Node.js 常用命令全攻略
node.js
前端双越老师7 天前
我从 0 开发的 AI Agent 智语项目发布了
前端·node.js·agent
kyriewen7 天前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
donecoding8 天前
3 条命令搞定闭环 Monorepo:Lerna 版本管理 + 拓扑构建 + 自定义分发
前端·前端框架·node.js