javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > js nodejs后端开发

JavaScript通过nodejs进行后端开发的过程

作者:@多弗朗明哥·汤姆

本文系统介绍了Node.js后端开发流程,涵盖环境搭建、HTTP服务器创建(http/Express)、路由中间件、数据库集成(MongoDB/MySQL)、JWT认证、文件上传、错误处理及部署(PM2/Docker),并提供项目结构建议,助你快速构建应用,感兴趣的朋友一起看看吧

使用 JavaScript 通过 Node.js 进行后端开发主要包括以下几个核心步骤和关键技术点:

一、基础环境搭建

1. 安装 Node.js

2. 初始化项目

mkdir my-backend
cd my-backend
npm init -y  # 生成 package.json

二、创建 HTTP 服务器

1. 原生http模块(基础示例)

// server.js
const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello from Node.js!');
});
server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

运行:node server.js

2. 使用 Express 框架(推荐)

安装 Express:

npm install express

 示例代码:

// app.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
  res.send('Hello from Express!');
});
app.listen(3000, () => {
  console.log('Express server running on port 3000');
});

三、核心功能实现

1. 路由处理

// 获取查询参数(如 /search?q=nodejs)
app.get('/search', (req, res) => {
  const query = req.query.q;
  res.send(`Searching for: ${query}`);
});
// 动态路由参数(如 /users/123)
app.get('/users/:id', (req, res) => {
  res.send(`User ID: ${req.params.id}`);
});
// POST 请求处理
app.post('/users', express.json(), (req, res) => {
  const userData = req.body;
  res.status(201).json({ id: 1, ...userData });
});

2. 中间件(Middleware)

// 日志中间件
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});
// 静态文件托管
app.use(express.static('public'));  // 访问 http://localhost:3000/image.jpg
// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Server Error!');
});

四、数据库集成

1. MongoDB(NoSQL)

安装 Mongoose:

npm install mongoose

示例代码:

const mongoose = require('mongoose');
// 连接数据库
mongoose.connect('mongodb://localhost:27017/mydb');
// 定义数据模型
const User = mongoose.model('User', {
  name: String,
  email: { type: String, unique: true }
});
// 创建用户
app.post('/users', async (req, res) => {
  try {
    const user = new User(req.body);
    await user.save();
    res.status(201).json(user);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

2. MySQL(SQL)

安装 mysql2

npm install mysql2

示例代码:

const mysql = require('mysql2/promise');
// 创建连接池
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'yourpassword',
  database: 'test'
});
// 查询示例
app.get('/products', async (req, res) => {
  const [rows] = await pool.query('SELECT * FROM products');
  res.json(rows);
});

五、用户认证(JWT)

安装依赖:

npm install jsonwebtoken bcryptjs

示例代码:

const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
// 模拟用户数据库
const users = [];
// 注册
app.post('/register', async (req, res) => {
  const hashedPassword = await bcrypt.hash(req.body.password, 10);
  users.push({
    username: req.body.username,
    password: hashedPassword
  });
  res.status(201).send('User registered');
});
// 登录
app.post('/login', async (req, res) => {
  const user = users.find(u => u.username === req.body.username);
  if (!user || !await bcrypt.compare(req.body.password, user.password)) {
    return res.status(401).send('Invalid credentials');
  }
  const token = jwt.sign({ username: user.username }, 'your-secret-key', {
    expiresIn: '1h'
  });
  res.json({ token });
});
// 受保护的路由
app.get('/profile', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).send('Unauthorized');
  try {
    const decoded = jwt.verify(token, 'your-secret-key');
    res.send(`Welcome, ${decoded.username}`);
  } catch (err) {
    res.status(401).send('Invalid token');
  }
});

六、文件上传

使用 multer 中间件:

npm install multer

示例代码:

const multer = require使用 JavaScript 通过 Node.js 进行后端开发,可以按照以下步骤和示例代码实现:
---
## **1. 基础准备**
### 1.1 安装 Node.js
- 下载安装包:[Node.js 官网](https://nodejs.org/)
- 验证安装:
  ```bash
  node -v  # 检查版本
  npm -v   # 检查包管理器

1.2 初始化项目

mkdir node-backend
cd node-backend
npm init -y  # 生成 package.json

2. 创建 HTTP 服务器

2.1 原生http模块(基础示例)

// server.js
const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, Node.js!');
});
server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

运行:

node server.js

2.2 使用 Express(推荐)

安装 Express:

npm install express

示例代码:

// app.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
  res.send('Hello, Express!');
});
app.listen(3000, () => {
  console.log('Express server running at http://localhost:3000');
});

3. 核心功能实现

3.1 路由处理

// 获取查询参数(如 /search?q=nodejs)
app.get('/search', (req, res) => {
  const query = req.query.q;
  res.send(`Search for: ${query}`);
});
// 动态路由(如 /users/123)
app.get('/users/:id', (req, res) => {
  res.send(`User ID: ${req.params.id}`);
});
// 处理 POST 请求
app.post('/login', (req, res) => {
  res.send('Login endpoint');
});

3.2 中间件(Middleware)

// 解析 JSON 请求体
app.use(express.json());
// 自定义中间件(记录请求日志)
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next(); // 继续执行后续逻辑
});

3.3 静态文件服务

app.use(express.static('public')); // 托管 public 文件夹

访问 http://localhost:3000/image.jpg 即可返回 public/image.jpg

4. 数据库交互

4.1 MongoDB(NoSQL)

安装 Mongoose:

npm install mongoose

示例代码:

const mongoose = require('mongoose');
// 连接数据库
mongoose.connect('mongodb://localhost:27017/mydb');
// 定义数据模型
const User = mongoose.model('User', {
  name: String,
  email: String
});
// 插入数据
app.post('/users', async (req, res) => {
  const user = new User(req.body);
  await user.save();
  res.status(201).send(user);
});
// 查询数据
app.get('/users', async (req, res) => {
  const users = await User.find();
  res.send(users);
});

4.2 MySQL(SQL)

安装 mysql2

npm install mysql2

示例代码:

const mysql = require('mysql2/promise');
// 创建连接池
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'test'
});
// 查询数据
app.get('/users', async (req, res) => {
  const [rows] = await pool.query('SELECT * FROM users');
  res.send(rows);
});

5. 用户认证(JWT)

安装依赖:

npm install jsonwebtoken bcryptjs

示例代码:

const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
// 模拟用户数据库
const users = [];
// 注册
app.post('/register', async (req, res) => {
  const hashedPassword = await bcrypt.hash(req.body.password, 10);
  users.push({ 
    username: req.body.username, 
    password: hashedPassword 
  });
  res.status(201).send('User registered');
});
// 登录
app.post('/login', async (req, res) => {
  const user = users.find(u => u.username === req.body.username);
  if (!user || !await bcrypt.compare(req.body.password, user.password)) {
    return res.status(401).send('Invalid credentials');
  }
  // 生成 JWT Token
  const token = jwt.sign({ username: user.username }, 'your-secret-key', { 
    expiresIn: '1h' 
  });
  res.send({ token });
});
// 受保护的路由
app.get('/profile', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(403).send('Token required');
  try {
    const decoded = jwt.verify(token, 'your-secret-key');
    res.send(`Welcome, ${decoded.username}`);
  } catch (err) {
    res.status(401).send('Invalid token');
  }
});

6. 错误处理

6.1 同步错误

app.get('/error', (req, res) => {
  throw new Error('Test error');
});

6.2 异步错误

app.get('/async-error', async (req, res, next) => {
  try {
    await someAsyncOperation();
  } catch (err) {
    next(err); // 传递给错误处理中间件
  }
});

6.3 全局错误处理

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

7. 部署上线

7.1 使用 PM2(进程管理)

安装:

npm install pm2 -g

启动服务:

pm2 start app.js --name "my-api"

常用命令:

pm2 logs       # 查看日志
pm2 restart all # 重启服务

7.2 Docker 容器化

创建 Dockerfile

FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]

构建并运行:

docker build -t node-app .
docker run -p 3000:3000 node-app

8. 项目结构建议

node-backend/
├── src/
│   ├── controllers/  # 业务逻辑
│   ├── models/       # 数据库模型
│   ├── routes/       # 路由定义
│   ├── middleware/   # 中间件
│   └── app.js        # 入口文件
├── .env              # 环境变量
├── package.json
└── README.md

总结

  1. 基础服务:用 httpExpress 创建服务器。
  2. 路由与中间件:处理请求、静态文件和日志。
  3. 数据库:集成 MongoDB 或 MySQL。
  4. 安全:JWT 认证和密码加密。
  5. 部署:通过 PM2 或 Docker 上线。

按照以上步骤,你可以快速构建一个完整的 Node.js 后端服务!

到此这篇关于JavaScript怎么通过nodejs进行后端开发的文章就介绍到这了,更多相关js nodejs后端开发内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文