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 复制代码
##
相关推荐
无责任此方_修行中11 小时前
谁动了我的数据?一个 Bug 背后的“一行代码”真凶
后端·node.js·debug
岁月宁静12 小时前
AI 语音合成技术实践:实现文本转语音实时流式播放
前端·vue.js·node.js
Never_Satisfied16 小时前
在JavaScript / HTML / Node.js中,post方式的Content-Type属性的text的三种编码
javascript·node.js·html
学习3人组19 小时前
Node.js模块化开发实训案例
node.js·编辑器·vim
思考的笛卡尔20 小时前
Node.js性能优化:从事件循环到内存管理
性能优化·node.js
孟陬1 天前
一个专业的前端如何在国内安装 `pnpm`
npm·node.js·bun
Moonbit1 天前
安装Wasm版的MoonBit工具链
后端·node.js·webassembly
4_0_42 天前
全栈视角:从零构建一个现代化的 Todo 应用
前端·node.js
杏花春雨江南2 天前
npm error Could not resolve dependency:
前端·npm·node.js