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 复制代码
##
相关推荐
艾小码15 小时前
手把手教你实现一个EventEmitter,彻底告别复杂事件管理!
前端·javascript·node.js
前端小哲16 小时前
MCP从入门到实战
node.js·ai编程
dasseinzumtode17 小时前
nestJS 使用ExcelJS 实现数据的excel导出功能
前端·后端·node.js
梅孔立1 天前
服务器不支持node.js16以上版本安装?用Docker轻松部署Node.js 20+环境运行Strapi项目
服务器·docker·node.js
XiaoMu_0011 天前
基于Node.js和Three.js的3D模型网页预览器
javascript·3d·node.js
卿·静1 天前
Node.js对接即梦AI实现“千军万马”视频
前端·javascript·人工智能·后端·node.js
lvlv_feifei1 天前
N8N macOS (Apple Silicon) 完整安装配置教程
node.js·workflow
Cosmoshhhyyy1 天前
Node.js 18+安装及Claude国内镜像使用、idea中claude插件下载指南
node.js
徐_三岁2 天前
关于npm的钩子函数
前端·npm·node.js
不买Huracan不改名2 天前
安装Codex(需要用npm)
前端·npm·node.js