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 复制代码
##
相关推荐
liangshanbo121521 小时前
面试题:如何优化 Webpack 的打包速度?
前端·webpack·node.js
2601_962177301 天前
Windows 安装 Codex CLI 入门级教程
人工智能·windows·node.js·ai编程
光影少年1 天前
RN与Flutter架构区别
前端·flutter·react native·react.js·架构·node.js
梅孔立2 天前
Codex 完整教程(Node.js安装 + npm安装Codex + DeepSeek配置 + 快捷键 + 设置)
前端·npm·node.js
晚风醉蝶2 天前
webpack 模块提取
前端·webpack·node.js·ast·逆向分析
YIAN3 天前
从 SSE 流式到结构化输出:LangChain 三大 OutputParser 与 ToolCall 方案全实战
前端·langchain·node.js
濮水大叔4 天前
Cabloy全栈框架的两个SSR入口:Vona集成式SSR vs Zova独立式SSR
typescript·node.js·全栈
怕浪猫4 天前
DeepSeek Harness 系列图解
面试·前端框架·node.js
百万蹄蹄向前冲4 天前
双端同步!云服务器装最新Node.js v26.10全过程追踪
服务器·人工智能·node.js
前端snow4 天前
ai agent--- 后端概念补充:Docker Compose、ElasticSearch、IK、BM25等
node.js