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 复制代码
##
相关推荐
汤姆Tom19 小时前
Node.js 版本管理、NPM 命令、与 NVM 完全指南
前端·npm·node.js
RoyLin2 天前
TypeScript设计模式:原型模式
前端·后端·node.js
RoyLin2 天前
TypeScript设计模式:单例模式
前端·后端·node.js
RoyLin2 天前
TypeScript设计模式:工厂方法模式
前端·后端·node.js
RoyLin2 天前
TypeScript设计模式:模板方法模式
前端·后端·node.js
RoyLin3 天前
TypeScript设计模式:适配器模式
前端·后端·node.js
RoyLin3 天前
TypeScript设计模式:迭代器模式
javascript·后端·node.js
前端双越老师3 天前
2025 年还有前端不会 Nodejs ?
node.js·agent·全栈
人工智能训练师3 天前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny073 天前
pnpm相对于npm,yarn的优势
前端·npm·node.js