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 复制代码
##
相关推荐
接着奏乐接着舞。18 分钟前
【Node】Cluster和死锁问题
node.js
不会敲代码138 分钟前
深入理解 LangChain 文本分割器:为什么 RecursiveCharacterTextSplitter 是 RAG 的标配
langchain·node.js
天外飞雨道沧桑1 小时前
Node.js在前端开发中扮演的角色
前端·node.js
神奇小梵1 小时前
CTFSHOW的node.js漏洞
node.js
zhensherlock16 小时前
Protocol Launcher 系列:Tally 快速计数器的深度集成
前端·javascript·typescript·node.js·自动化·github·js
接着奏乐接着舞。20 小时前
【Node】用来处理CPU密集型任务的利器Worker Threads
node.js
不会敲代码11 天前
RAG 进阶:从网页加载到智能文档分割
langchain·node.js
heyCHEEMS1 天前
记录一下自动化构建中 SSE 与子进程管理的三个坑
javascript·node.js
qq_229058011 天前
Volta的下载、安装使用教程
node.js
zh_xuan1 天前
node.js搭建http服务
node.js