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 小时前
⚡️ 后端工程师的护甲:TypeScript 进阶与数据建模
前端·javascript·程序人生·typescript·前端框架·node.js·改行学it
程序员小易16 小时前
前端轮子(1)--前端部署后-判断页面是否为最新
前端·vue.js·node.js
Lovely Ruby17 小时前
[前端] 封装一下 echart 6,发布到 npm
前端·npm·node.js
BD_Marathon17 小时前
NPM_常见命令
前端·npm·node.js
程序员爱钓鱼20 小时前
Node.js 编程实战:图像与文件上传下载
前端·后端·node.js
程序员爱钓鱼20 小时前
Node.js 编程实战:日志管理与分析
后端·面试·node.js
vipbic1 天前
Strapi 5 怎么用才够爽?这款插件带你实现“建站自由”
后端·node.js
趴在窗边数星星1 天前
Koa 源码深度解析:带你理解 Koa 的设计哲学和核心实现原理
node.js
程序员爱钓鱼2 天前
Node.js 编程实战:CSV&JSON &Excel 数据处理
前端·后端·node.js
敢敢のwings2 天前
MCP Node.js SDK 全栈开发环境搭建详解
node.js