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 复制代码
##
相关推荐
aidou13141 小时前
Visual Studio Code(VS Code)安装步骤
vscode·npm·node.js·环境变量
止观止3 小时前
告别 require!TypeScript 5.9 与 Node.js 20+ 的 ESM 互操作指南
javascript·typescript·node.js
一只专注api接口开发的技术猿3 小时前
淘宝商品详情API的流量控制与熔断机制:保障系统稳定性的后端设计
大数据·数据结构·数据库·架构·node.js
天远数科7 小时前
天远车辆过户查询API集成指南:Node.js 全栈视角下的二手车数据挖掘
大数据·数据挖掘·node.js·vim
全栈小58 小时前
【前端】win11操作系统安装完最新版本的NodeJs运行npm install报错,提示在此系统上禁止运行脚本
前端·npm·node.js
莫有杯子的龙潭峡谷1 天前
在 Windows 系统上安装 OpenClaw
人工智能·node.js·安装教程·openclaw
朝朝暮暮an1 天前
Node.js-第一天学习内容
node.js
lichenyang4531 天前
Node.js AI 开发入门 - 完整学习笔记
人工智能·学习·node.js
岁岁种桃花儿1 天前
NodeJs从入门到上天:什么是Node.js
前端·node.js
一心赚狗粮的宇叔2 天前
VScode常用扩展包&Node.js安装及npm包安装
vscode·npm·node.js·web