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 复制代码
##
相关推荐
轮回的秋10 小时前
nvm 管理多版本node
node.js·nvm
s***558115 小时前
如何自由切换 Node.js 版本?
node.js
小小前端_我自坚强2 天前
渐进增强、优雅降级及现代Web开发技术详解
javascript·node.js
b***9102 天前
Node.js卸载超详细步骤(附图文讲解)
node.js
mixboot2 天前
配置 Node.js npm镜像源 安装 Claude Code
npm·node.js·nvm·claude code
q***71012 天前
如何在Windows系统上安装和配置Node.js及Node版本管理器(nvm)
windows·node.js
q***06472 天前
最新最详细的配置Node.js环境教程
node.js
希冀1232 天前
Node.js学习
前端·学习·node.js
Never_Satisfied2 天前
在JavaScript / Node.js中,Node.js的依赖项在跨平台时需要解决的问题
开发语言·javascript·node.js
梦想平凡2 天前
宝塔面板搭建 Node.js + MongoDB + Redis 环境
redis·mongodb·node.js