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 复制代码
##
相关推荐
__zRainy__4 小时前
Node系列 · Node基础:net 模块
后端·node.js
嘟嘟071712 小时前
从浏览器到 hello world:Docker + nginx 反向代理 + Node 最小服务器一次讲清
docker·容器·node.js
FungLeo12 小时前
Node 后端实战 · 老系统数据迁移怎么不出乱子?V1→V2 重构实战与 3 个生产坑
node.js·serverless·数据库迁移·d1 数据库
今日无bug12 小时前
Tool Use 工具调用 —— 让LLM缸中大脑突破物理限制的3个阶段
node.js·llm·agent
To_OC1 天前
装完 ESLint 它一声不吭?我还以为代码写得多好
后端·node.js·eslint
FungLeo1 天前
Node 后端实战 · 列表查询到底怎么写?一个通用 DSL 封装,过滤分页排序一次搞定
数据库·node.js·serverless·dsl 封装·通用列表查询
_codemonster1 天前
npm run dev 是在开发模式运行,怎么在生产环境运行
前端·npm·node.js
渔夫正在掘金1 天前
Cordis 插件热插拔能力深度解析
后端·node.js
嘟嘟07172 天前
NestJS 入门:从 NestFactory 入口到 Module/Controller/Service 模块化结构一次讲清
typescript·node.js·nestjs
breeze jiang2 天前
NestJS MVC 实战:用 hello 项目 7 个文件讲清分层、装饰器、依赖注入与错误处理
node.js·mvc·js