JavaScript通過nodejs進行后端開發(fā)的過程
使用 JavaScript 通過 Node.js 進行后端開發(fā)主要包括以下幾個核心步驟和關(guān)鍵技術(shù)點:
一、基礎(chǔ)環(huán)境搭建
1. 安裝 Node.js
- 從 Node.js 官網(wǎng) 下載并安裝最新 LTS 版本
- 驗證安裝:
node -v # 檢查 Node.js 版本 npm -v # 檢查 npm 版本
2. 初始化項目
mkdir my-backend cd my-backend npm init -y # 生成 package.json
二、創(chuàng)建 HTTP 服務(wù)器
1. 原生http模塊(基礎(chǔ)示例)
// 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');
});三、核心功能實現(xiàn)
1. 路由處理
// 獲取查詢參數(shù)(如 /search?q=nodejs)
app.get('/search', (req, res) => {
const query = req.query.q;
res.send(`Searching for: ${query}`);
});
// 動態(tài)路由參數(shù)(如 /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();
});
// 靜態(tài)文件托管
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!');
});四、數(shù)據(jù)庫集成
1. MongoDB(NoSQL)
安裝 Mongoose:
npm install mongoose
示例代碼:
const mongoose = require('mongoose');
// 連接數(shù)據(jù)庫
mongoose.connect('mongodb://localhost:27017/mydb');
// 定義數(shù)據(jù)模型
const User = mongoose.model('User', {
name: String,
email: { type: String, unique: true }
});
// 創(chuàng)建用戶
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');
// 創(chuàng)建連接池
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');
// 模擬用戶數(shù)據(jù)庫
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 進行后端開發(fā),可以按照以下步驟和示例代碼實現(xiàn): --- ## **1. 基礎(chǔ)準備** ### 1.1 安裝 Node.js - 下載安裝包:[Node.js 官網(wǎng)](https://nodejs.org/) - 驗證安裝: ```bash node -v # 檢查版本 npm -v # 檢查包管理器
1.2 初始化項目
mkdir node-backend cd node-backend npm init -y # 生成 package.json
2. 創(chuàng)建 HTTP 服務(wù)器
2.1 原生http模塊(基礎(chǔ)示例)
// 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. 核心功能實現(xiàn)
3.1 路由處理
// 獲取查詢參數(shù)(如 /search?q=nodejs)
app.get('/search', (req, res) => {
const query = req.query.q;
res.send(`Search for: ${query}`);
});
// 動態(tài)路由(如 /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(); // 繼續(xù)執(zhí)行后續(xù)邏輯
});3.3 靜態(tài)文件服務(wù)
app.use(express.static('public')); // 托管 public 文件夾訪問 http://localhost:3000/image.jpg 即可返回 public/image.jpg。
4. 數(shù)據(jù)庫交互
4.1 MongoDB(NoSQL)
安裝 Mongoose:
npm install mongoose
示例代碼:
const mongoose = require('mongoose');
// 連接數(shù)據(jù)庫
mongoose.connect('mongodb://localhost:27017/mydb');
// 定義數(shù)據(jù)模型
const User = mongoose.model('User', {
name: String,
email: String
});
// 插入數(shù)據(jù)
app.post('/users', async (req, res) => {
const user = new User(req.body);
await user.save();
res.status(201).send(user);
});
// 查詢數(shù)據(jù)
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');
// 創(chuàng)建連接池
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test'
});
// 查詢數(shù)據(jù)
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');
// 模擬用戶數(shù)據(jù)庫
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
啟動服務(wù):
pm2 start app.js --name "my-api"
常用命令:
pm2 logs # 查看日志 pm2 restart all # 重啟服務(wù)
7.2 Docker 容器化
創(chuàng)建 Dockerfile:
FROM node:18 WORKDIR /app COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 CMD ["node", "app.js"]
構(gòu)建并運行:
docker build -t node-app . docker run -p 3000:3000 node-app
8. 項目結(jié)構(gòu)建議
node-backend/ ├── src/ │ ├── controllers/ # 業(yè)務(wù)邏輯 │ ├── models/ # 數(shù)據(jù)庫模型 │ ├── routes/ # 路由定義 │ ├── middleware/ # 中間件 │ └── app.js # 入口文件 ├── .env # 環(huán)境變量 ├── package.json └── README.md
總結(jié)
- 基礎(chǔ)服務(wù):用
http或Express創(chuàng)建服務(wù)器。 - 路由與中間件:處理請求、靜態(tài)文件和日志。
- 數(shù)據(jù)庫:集成 MongoDB 或 MySQL。
- 安全:JWT 認證和密碼加密。
- 部署:通過 PM2 或 Docker 上線。
按照以上步驟,你可以快速構(gòu)建一個完整的 Node.js 后端服務(wù)!
到此這篇關(guān)于JavaScript怎么通過nodejs進行后端開發(fā)的文章就介紹到這了,更多相關(guān)js nodejs后端開發(fā)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JS實現(xiàn)遠程控制的基本原理和實現(xiàn)方法
遠程控制是指通過網(wǎng)絡(luò)等遠距離通訊手段控制另一設(shè)備的操作行為,在現(xiàn)實生活中,隨著物聯(lián)網(wǎng)技術(shù)的不斷發(fā)展,遠程控制技術(shù)越來越重要,本文將詳細介紹?JS?實現(xiàn)遠程控制的基本原理、開發(fā)流程和實現(xiàn)方法,需要的朋友可以參考下2023-06-06
javascript判斷ie瀏覽器6/7版本加載不同樣式表的實現(xiàn)代碼
ie6/ie7的兼容問題很讓人苦惱,我們可以針對這兩個版本的瀏覽器單獨寫?yīng)毩⒌臉邮奖?,來解決兼容問題。這里的例子以判斷ie6與ie7來加載不同的樣式表2011-12-12
JS腳本實現(xiàn)定時到網(wǎng)站上簽到/簽退功能
這篇文章主要介紹了JS腳本實現(xiàn)定時到網(wǎng)站上簽到/簽退功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04
[js高手之路]HTML標簽解釋成DOM節(jié)點的實現(xiàn)方法
下面小編就為大家?guī)硪黄猍js高手之路]HTML標簽解釋成DOM節(jié)點的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
JS實現(xiàn)雙擊內(nèi)容變?yōu)榭删庉嫚顟B(tài)
在一些網(wǎng)站上我們經(jīng)??吹浇换バ院軓姷墓δ?。一些用戶資料可以直接雙擊出現(xiàn)文本框,并在此輸入新的資料即可修改,無需再按確定按鈕等。怎么實現(xiàn)的呢?今天小編給大家分享JS實現(xiàn)雙擊內(nèi)容變?yōu)榭删庉嫚顟B(tài),需要的的朋友參考下2017-03-03

