欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript通過(guò)nodejs進(jìn)行后端開(kāi)發(fā)的過(guò)程

 更新時(shí)間:2025年06月30日 14:54:56   作者:@多弗朗明哥·湯姆  
本文系統(tǒng)介紹了Node.js后端開(kāi)發(fā)流程,涵蓋環(huán)境搭建、HTTP服務(wù)器創(chuàng)建(http/Express)、路由中間件、數(shù)據(jù)庫(kù)集成(MongoDB/MySQL)、JWT認(rèn)證、文件上傳、錯(cuò)誤處理及部署(PM2/Docker),并提供項(xiàng)目結(jié)構(gòu)建議,助你快速構(gòu)建應(yīng)用,感興趣的朋友一起看看吧

使用 JavaScript 通過(guò) Node.js 進(jìn)行后端開(kāi)發(fā)主要包括以下幾個(gè)核心步驟和關(guān)鍵技術(shù)點(diǎn):

一、基礎(chǔ)環(huán)境搭建

1. 安裝 Node.js

  • Node.js 官網(wǎng) 下載并安裝最新 LTS 版本
  • 驗(yàn)證安裝:
  • node -v  # 檢查 Node.js 版本
    npm -v   # 檢查 npm 版本

2. 初始化項(xiàng)目

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');
});

運(yùn)行: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');
});

三、核心功能實(shí)現(xiàn)

1. 路由處理

// 獲取查詢(xún)參數(shù)(如 /search?q=nodejs)
app.get('/search', (req, res) => {
  const query = req.query.q;
  res.send(`Searching for: ${query}`);
});
// 動(dòng)態(tài)路由參數(shù)(如 /users/123)
app.get('/users/:id', (req, res) => {
  res.send(`User ID: ${req.params.id}`);
});
// POST 請(qǐng)求處理
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'));  // 訪(fǎng)問(wèn) http://localhost:3000/image.jpg
// 錯(cuò)誤處理中間件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Server Error!');
});

四、數(shù)據(jù)庫(kù)集成

1. MongoDB(NoSQL)

安裝 Mongoose:

npm install mongoose

示例代碼:

const mongoose = require('mongoose');
// 連接數(shù)據(jù)庫(kù)
mongoose.connect('mongodb://localhost:27017/mydb');
// 定義數(shù)據(jù)模型
const User = mongoose.model('User', {
  name: String,
  email: { type: String, unique: true }
});
// 創(chuàng)建用戶(hù)
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'
});
// 查詢(xún)示例
app.get('/products', async (req, res) => {
  const [rows] = await pool.query('SELECT * FROM products');
  res.json(rows);
});

五、用戶(hù)認(rèn)證(JWT)

安裝依賴(lài):

npm install jsonwebtoken bcryptjs

示例代碼:

const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
// 模擬用戶(hù)數(shù)據(jù)庫(kù)
const users = [];
// 注冊(cè)
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 });
});
// 受保護(hù)的路由
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 通過(guò) Node.js 進(jìn)行后端開(kāi)發(fā),可以按照以下步驟和示例代碼實(shí)現(xiàn):
---
## **1. 基礎(chǔ)準(zhǔn)備**
### 1.1 安裝 Node.js
- 下載安裝包:[Node.js 官網(wǎng)](https://nodejs.org/)
- 驗(yàn)證安裝:
  ```bash
  node -v  # 檢查版本
  npm -v   # 檢查包管理器

1.2 初始化項(xiàng)目

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');
});

運(yùn)行:

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. 核心功能實(shí)現(xiàn)

3.1 路由處理

// 獲取查詢(xún)參數(shù)(如 /search?q=nodejs)
app.get('/search', (req, res) => {
  const query = req.query.q;
  res.send(`Search for: ${query}`);
});
// 動(dòng)態(tài)路由(如 /users/123)
app.get('/users/:id', (req, res) => {
  res.send(`User ID: ${req.params.id}`);
});
// 處理 POST 請(qǐng)求
app.post('/login', (req, res) => {
  res.send('Login endpoint');
});

3.2 中間件(Middleware)

// 解析 JSON 請(qǐng)求體
app.use(express.json());
// 自定義中間件(記錄請(qǐng)求日志)
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 文件夾

訪(fǎng)問(wèn) http://localhost:3000/image.jpg 即可返回 public/image.jpg。

4. 數(shù)據(jù)庫(kù)交互

4.1 MongoDB(NoSQL)

安裝 Mongoose:

npm install mongoose

示例代碼:

const mongoose = require('mongoose');
// 連接數(shù)據(jù)庫(kù)
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);
});
// 查詢(xún)數(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'
});
// 查詢(xún)數(shù)據(jù)
app.get('/users', async (req, res) => {
  const [rows] = await pool.query('SELECT * FROM users');
  res.send(rows);
});

5. 用戶(hù)認(rèn)證(JWT)

安裝依賴(lài):

npm install jsonwebtoken bcryptjs

示例代碼:

const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
// 模擬用戶(hù)數(shù)據(jù)庫(kù)
const users = [];
// 注冊(cè)
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 });
});
// 受保護(hù)的路由
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. 錯(cuò)誤處理

6.1 同步錯(cuò)誤

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

6.2 異步錯(cuò)誤

app.get('/async-error', async (req, res, next) => {
  try {
    await someAsyncOperation();
  } catch (err) {
    next(err); // 傳遞給錯(cuò)誤處理中間件
  }
});

6.3 全局錯(cuò)誤處理

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

7. 部署上線(xiàn)

7.1 使用 PM2(進(jìn)程管理)

安裝:

npm install pm2 -g

啟動(dòng)服務(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)建并運(yùn)行:

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

8. 項(xiàng)目結(jié)構(gòu)建議

node-backend/
├── src/
│   ├── controllers/  # 業(yè)務(wù)邏輯
│   ├── models/       # 數(shù)據(jù)庫(kù)模型
│   ├── routes/       # 路由定義
│   ├── middleware/   # 中間件
│   └── app.js        # 入口文件
├── .env              # 環(huán)境變量
├── package.json
└── README.md

總結(jié)

  1. 基礎(chǔ)服務(wù):用 httpExpress 創(chuàng)建服務(wù)器。
  2. 路由與中間件:處理請(qǐng)求、靜態(tài)文件和日志。
  3. 數(shù)據(jù)庫(kù):集成 MongoDB 或 MySQL。
  4. 安全:JWT 認(rèn)證和密碼加密。
  5. 部署:通過(guò) PM2 或 Docker 上線(xiàn)。

按照以上步驟,你可以快速構(gòu)建一個(gè)完整的 Node.js 后端服務(wù)!

到此這篇關(guān)于JavaScript怎么通過(guò)nodejs進(jìn)行后端開(kāi)發(fā)的文章就介紹到這了,更多相關(guān)js nodejs后端開(kāi)發(fā)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 小程序的上傳文件接口的注意要點(diǎn)解析

    小程序的上傳文件接口的注意要點(diǎn)解析

    這篇文章主要介紹了小程序的上傳文件接口的注意解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09
  • JS實(shí)現(xiàn)遠(yuǎn)程控制的基本原理和實(shí)現(xiàn)方法

    JS實(shí)現(xiàn)遠(yuǎn)程控制的基本原理和實(shí)現(xiàn)方法

    遠(yuǎn)程控制是指通過(guò)網(wǎng)絡(luò)等遠(yuǎn)距離通訊手段控制另一設(shè)備的操作行為,在現(xiàn)實(shí)生活中,隨著物聯(lián)網(wǎng)技術(shù)的不斷發(fā)展,遠(yuǎn)程控制技術(shù)越來(lái)越重要,本文將詳細(xì)介紹?JS?實(shí)現(xiàn)遠(yuǎn)程控制的基本原理、開(kāi)發(fā)流程和實(shí)現(xiàn)方法,需要的朋友可以參考下
    2023-06-06
  • 淺析JavaScript中五種模塊系統(tǒng)的使用

    淺析JavaScript中五種模塊系統(tǒng)的使用

    模塊系統(tǒng)是什么?簡(jiǎn)單來(lái)說(shuō),其實(shí)就是我們?cè)谝粋€(gè)文件里寫(xiě)代碼,聲明一些可以導(dǎo)出的字段,然后另一個(gè)文件可以將其導(dǎo)入并使用。今天我們來(lái)聊聊?JavaScript?的模塊系統(tǒng),感興趣的可以了解一下
    2022-11-11
  • js判斷移動(dòng)端橫豎屏視口檢測(cè)實(shí)現(xiàn)的幾種方法

    js判斷移動(dòng)端橫豎屏視口檢測(cè)實(shí)現(xiàn)的幾種方法

    最近做歌一個(gè)小項(xiàng)目,但是要放到我們的app上,然而需要橫豎屏使用不同的樣式,本文就來(lái)介紹一下js判斷移動(dòng)端橫豎屏視口檢測(cè)實(shí)現(xiàn)的幾種方法,感興趣的可以了解一下
    2021-07-07
  • javascript判斷ie瀏覽器6/7版本加載不同樣式表的實(shí)現(xiàn)代碼

    javascript判斷ie瀏覽器6/7版本加載不同樣式表的實(shí)現(xiàn)代碼

    ie6/ie7的兼容問(wèn)題很讓人苦惱,我們可以針對(duì)這兩個(gè)版本的瀏覽器單獨(dú)寫(xiě)?yīng)毩⒌臉邮奖恚瑏?lái)解決兼容問(wèn)題。這里的例子以判斷ie6與ie7來(lái)加載不同的樣式表
    2011-12-12
  • JS腳本實(shí)現(xiàn)定時(shí)到網(wǎng)站上簽到/簽退功能

    JS腳本實(shí)現(xiàn)定時(shí)到網(wǎng)站上簽到/簽退功能

    這篇文章主要介紹了JS腳本實(shí)現(xiàn)定時(shí)到網(wǎng)站上簽到/簽退功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-04-04
  • js實(shí)現(xiàn)圖片上傳并預(yù)覽功能

    js實(shí)現(xiàn)圖片上傳并預(yù)覽功能

    這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)圖片上傳并預(yù)覽功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-08-08
  • [js高手之路]HTML標(biāo)簽解釋成DOM節(jié)點(diǎn)的實(shí)現(xiàn)方法

    [js高手之路]HTML標(biāo)簽解釋成DOM節(jié)點(diǎn)的實(shí)現(xiàn)方法

    下面小編就為大家?guī)?lái)一篇[js高手之路]HTML標(biāo)簽解釋成DOM節(jié)點(diǎn)的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-08-08
  • 手機(jī)端js和html5刮刮卡效果

    手機(jī)端js和html5刮刮卡效果

    這篇文章主要為大家詳細(xì)介紹了手機(jī)端js和html5刮刮卡效果,刮開(kāi)之后是隨機(jī)生成的8位碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-01-01
  • JS實(shí)現(xiàn)雙擊內(nèi)容變?yōu)榭删庉嫚顟B(tài)

    JS實(shí)現(xiàn)雙擊內(nèi)容變?yōu)榭删庉嫚顟B(tài)

    在一些網(wǎng)站上我們經(jīng)??吹浇换バ院軓?qiáng)的功能。一些用戶(hù)資料可以直接雙擊出現(xiàn)文本框,并在此輸入新的資料即可修改,無(wú)需再按確定按鈕等。怎么實(shí)現(xiàn)的呢?今天小編給大家分享JS實(shí)現(xiàn)雙擊內(nèi)容變?yōu)榭删庉嫚顟B(tài),需要的的朋友參考下
    2017-03-03

最新評(píng)論