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 复制代码
# 依赖
[email protected] D:\node.js-res\devops\myapp
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

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}`);
});
相关推荐
码农捻旧2 天前
解决Mongoose “Cannot overwrite model once compiled“ 错误的完整指南
javascript·数据库·mongodb·node.js·express
HWL56793 天前
Express项目解决跨域问题
前端·后端·中间件·node.js·express
程序员拂雨5 天前
Express知识框架
node.js·express
layman05287 天前
node.js 实战——餐厅静态主页编写(express+node+ejs+bootstrap)
node.js·bootstrap·express
layman05289 天前
node.js 实战——express图片保存到本地或服务器(七牛云、腾讯云、阿里云)
node.js·express
小妖66611 天前
express 怎么搭建 WebSocket 服务器
websocket·网络协议·express
一袋米扛几楼9819 天前
【前端】从零开始的搭建顺序指南(技术栈:Node.js + Express + MongoDB + React)book-management
前端·node.js·express
layman052819 天前
node.js 实战——从0开始做一个餐厅预订(express+node+ejs+bootstrap)
node.js·express
白昼的星光@20 天前
使用nodeJs的express+axios+cors做代理
express
键盘飞行员21 天前
使用 Node、Express 和 MongoDB 构建一个项目工程
数据库·mongodb·express