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 复制代码
##
相关推荐
半个落月7 小时前
从 Tokenization 到 Embedding:用 Node.js 搞懂大模型为什么先“分词”再“向量化”
人工智能·node.js
叁两1 天前
前端转型AI Agent该如何学习?(前置篇)
前端·人工智能·node.js
糖拌西瓜皮1 天前
TypeScript 进阶:泛型、条件类型、类型守卫与装饰器
javascript·node.js
米丘4 天前
vite8 vite preview 命令做了什么?
node.js·vite
blanks20205 天前
生成 公钥私钥 笔记
node.js
糖拌西瓜皮6 天前
Java开发者视角:深入理解Node.js异步编程模型
java·后端·node.js
智通7 天前
Node.js事件循环核心机制
node.js
初圣魔门首席弟子7 天前
Node.js 详细介绍(知识库版)
windows·qt·node.js·知识库
糖拌西瓜皮7 天前
Java 开发者如何快速上手 Node.js:一份从入门到进阶的学习路线
node.js
yspwf7 天前
NestJS 配置管理完整方案
后端·架构·node.js