node.js 之Express 框架基础

官网

node.js 比较流行的框架是Express ,和Python的Flask类似。

bash 复制代码
## 中文网
https://www.expressjs.com.cn/


## 官网
https://expressjs.com/

## 查询mysql返回json示例
https://blog.csdn.net/knight_zhou/article/details/139013695

环境

bash 复制代码
mkdir myapp
npm init

##
npm install express --save

基础

路由

javascript 复制代码
// GET method route
app.get('/', function (req, res) {
  res.send('GET request to the homepage')
})

// POST method route
app.post('/', function (req, res) {
  res.send('POST request to the homepage')
})

静态文件

javascript 复制代码
/*
 powershell启动: $env:DEBUG='myapp:*'; npm start
 或者这样启动: node.exe .\bin\www
*/

// curl 127.0.0.1:3000/static
app.use('/static',express.static(path.join(__dirname, 'public')));    // 静态文件目录

模板渲染

bash 复制代码
# 官网
https://expressjs.com/en/guide/using-template-engines.html

支持如下三种模板引擎:

读取数据库配置文件

bash 复制代码
# 依赖
myapp@1.0.0 D:\node.js-res\devops\myapp
├── config@3.3.11
├── express@4.19.2
├── mysql@2.18.1
├── nconf@0.12.1
└── redis@4.6.14

config.js

javascript 复制代码
{
    "mysql_info": {
      "host": "localhost",
      "user": "root",
      "password": "root",
      "database":"db_devops"
    },
    "redis_info":{
      "url":"redis://10.10.10.14:6379",
      "password":"123456"
    }
}

app.js

javascript 复制代码
const express = require('express');
const mysql = require('mysql');
const redis = require('redis');
const fs = require('fs');
const path = require('path');

// 读取配置文件
const configPath = path.join(__dirname, 'config.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));

 
// 配置MySQL连接
const connection = mysql.createConnection({
  host     : config.mysql_info.host,
  user     : config.mysql_info.user,
  password : config.mysql_info.password,
  database: config.mysql_info.database
});
 
// 连接MySQL
connection.connect();

// 创建一个客户端连接到Redis服务器
const client = redis.createClient({
  url: config.redis_info.url, // 替换为你的Redis服务器地址和端口
  // username: "knight",
  password: config.redis_info.password
});
 
// 监听错误
client.on('error', (err) => {
  console.log('Redis Client Error', err);
});
 
// 连接到Redis
client.connect();
 
// 设置键值对

const app = express();
const port = 1234;
 
// 查询数据的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格式返回
  });
});

// redis
app.get('/api/redis', (req, res) => {
  client.set('name', 'vego', redis.print);
  console.log('test insert redis');
  res.send("ok");
});
 
// 启动服务器
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
相关推荐
茶茶只知道学习7 天前
Express中间件和路由及响应方法
中间件·express
计算机毕设定制辅导-无忧学长11 天前
InfluxDB 与 Node.js 框架:Express 集成方案(二)
node.js·express
啃火龙果的兔子13 天前
Node.js (Express) + MySQL + Redis构建项目流程
mysql·node.js·express
计算机毕设定制辅导-无忧学长15 天前
InfluxDB 与 Node.js 框架:Express 集成方案(一)
node.js·express
gongzemin17 天前
使用Node.js开发微信第三方平台后台
微信小程序·node.js·express
都给我19 天前
服务器中涉及节流(Throttle)的硬件组件及其应用注意事项
服务器·网络·express
Littlewith1 个月前
Node.js:Web模块、Express框架
java·开发语言·前端·c++·后端·node.js·express
Fireworkitte1 个月前
node.js 为什么要装 express组件
node.js·express
古怪今人1 个月前
NodeJS Express 静态文件、中间件、路由案例
中间件·express
congvee1 个月前
express学习第2期 - dotenv 加载配置文件
express