nodejs 路由/請求

//導入模塊
const express = require('express');
//創建應用
const app =  express();//設置路由
app.get('/',(req,resp)=>{//輸出響應console.log('request coming.............');resp.json(req.headers);
});app.get('/user/:id', (req, res) => {const userId = req.params.id; // 獲取 URL 中的路由參數res.send(`User ID: ${userId}`);
});app.get('/user/userId', (req,resp) => { resp.json({method: req.method,path: req.path,url: req.url,query: req.query,params: req.params,headers: req.headers,cookies: req.cookies,ip: req.ip || req.ips});
}); app.get('/user2/:id/name/:name', (req, res) => {const userId = req.params.id; // 獲取 URL 中的路由參數res.send(`User ID: ${userId}`);
});//多個路由函數app.get('/tt', (req,resp,next) => { console.log('${req.method} ${req.path}');next();
}, (req, resp) => {resp.send('首頁');
});function logger(req, resp, next) { console.log('${req.method} ${req.path}');next();
};function home(req, resp) { resp.send('首頁');
}app.get('/tt2', [logger, home]);//公共路由
app.get('/usr/login', (req, resp) => { resp.send('登錄頁面');
});
app.post('/usr/login', (req, resp) => { resp.send('登錄處理');
});
//將上面的兩個總方法合并為一個
app.route().get((req, resp) => { resp.send('登錄頁面');}).post((req, resp) => {resp.send('登錄處理');});app.listen(8080,()=>{console.log('listening on 8080');
});

模塊化路由

//Express 提供的Router 對象可以實現路由和入口JS的解耦,用于模塊化的路由有以下有點:
const express = require('express');
const router = express.Router();
router.get('/login', (req,resp) => { console.log('${req.method} ${req.path}');resp.send('登錄');
});router.get('/register', (req,resp) => { console.log('${req.method} ${req.path}');resp.send('注冊');
});module.exports = router;    =====================================const express = require('express');
const router = express.Router();
router.get('/list', (req,resp) => { console.log('${req.method} ${req.path}');resp.send('動態列表');
});
module.exports = router;    
=================================const express = require('express');
const router = express.Router();
router.get('/list', (req,resp) => { console.log('${req.method} ${req.path}');resp.send('動態列表');
});
module.exports = router;    =========================================
//導入模塊
const express = require('express');
//創建應用
const app = express();const user = require('./user');
const timeline = require('./timeline');app.use('/user', user);
app.use('/timeline',timeline);app.listen(8080,()=>{console.log('listening on 8080');
});//上面的代碼最終會生成一下路由
// get /user/login
// get /user /register
// get /timeline/list

=============================================
請求獲取cookie
安裝cookie-parser
C:\Users\Administrator\Desktop\expres-example>npm install cookie-parser --save
added 2 packages in 3s
14 packages are looking for funding
run npm fund for details
編寫代碼

//導入模塊
const express = require('express');
const cookieParser = require('cookie-parser');
//創建應用
const app = express();
app.use(cookieParser());
app.get('/',(req,resp)=>{//輸出響應console.log('request coming.............');resp.json({cookies: req.cookies});
});app.listen(8080,()=>{console.log('listening on 8080');
});

在這里插入圖片描述
獲取請求體
安裝 body-parser
C:\Users\Administrator\Desktop\expres-example>npm install body-parser --save
up to date in 2s
14 packages are looking for funding
run npm fund for details
編寫代碼

//導入模塊
const express = require(‘express’);
const cookieParser = require(‘cookie-parser’);
const bodyParser = require(‘body-parser’);
//創建應用
const app = express();
app.use(cookieParser());
app.use(bodyParser());
app.get(‘/’,(req,resp)=>{
//輸出響應
console.log(‘request coming…’);
resp.json({cookies: req.cookies});
});

Express 4.16.0版本開始 新版本已經不能使用了 報錯如下

Error: The bodyParser() generic has been split into individual middleware to use instead.
at bodyParser (c:\Users\Administrator\Desktop\expres-example\node_modules\body-parser\index.js:79:9)
at Object. (c:\Users\Administrator\Desktop\expres-example\src\cookie.js:8:9)
at Module._compile (node:internal/modules/cjs/loader:1730:14)
at Object…js (node:internal/modules/cjs/loader:1895:10)
at Module.load (node:internal/modules/cjs/loader:1465:32)
案例:
const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const app = express();

// 解析 application/json 類型的數據
app.use(bodyParser.json());

// 解析 application/x-www-form-urlencoded 類型的數據
app.use(bodyParser.urlencoded({ extended: true }));

app.post(‘/your-endpoint’, (req, res) => {
console.log(req.body); // 這里可以訪問到POST請求的body參數
res.send(‘Data received’);
});

app.listen(3000, () => {
console.log(‘Server is running on port 3000’);
});

====================================

express  原始方式的post請求 參數獲取
//導入模塊
const express = require('express');
const cookieParser = require('cookie-parser');
//const bodyParser = require('body-parser');
//創建應用
const app = express();
app.use(cookieParser());
// 解析application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));// 解析 application/json
app.use(express.json());  //app.use(bodyParser());
app.get('/',(req,resp)=>{//輸出響應console.log('request coming.............');resp.json({cookies: req.cookies});
});
app.post('/user',(req,resp)=>{//輸出響應console.log('request coming.............');resp.json(req.body);
});
app.listen(8080,()=>{console.log('listening on 8080');
});

使用raw-body中間件(對于非JSON/URL編碼的body)
如果你需要處理非JSON或URL編碼格式的body(例如,原始的二進制數據),你可以使用raw-body中間件。首先,安裝raw-body

npm install raw-body
const express = require('express');
const rawBody = require('raw-body');
const app = express();app.use((req, res, next) => {rawBody(req, {length: req.headers['content-length'],limit: '1mb', // 設置最大限制大小,防止內存溢出encoding: rawBody.TEXT // 或者 rawBody.RAW,根據需要選擇文本或原始二進制數據格式}, (err, string) => {if (err) return next(err); // 處理錯誤情況req.text = string; // 將解析后的文本或二進制數據添加到req對象上,以便后續處理next(); // 繼續執行下一個中間件或路由處理函數});
});app.post('/your-endpoint', (req, res) => {console.log(req.text); // 這里可以訪問到POST請求的原始body數據(文本或二進制)res.send('Data received');
});app.listen(3000, () => {console.log('Server is running on port 3000');
});

==========================================
響應對象:
repsonse.status() 響應狀態
response.set(field[,value]) 設置響應包頭
response.download() 通過設置 Content-Disposition 響應頭提示客戶端下載
response.download(path[,filename],[,option],[,callback])

app.get('/download', function(req, res) {var filePath = '/path/to/file'; // 文件路徑var fileName = 'example.txt'; // 可選的文件名res.download(filePath, fileName);
});

response.end() 結束響應
response.redirect() 重定向
response.render() 頁面渲染
response.cookie() 設置cookie
cookie 包含的屬性:
name
value
options 選項:
domain 域名
expire GMT 到期時間,如果沒有設置或者為0 ,則關閉瀏覽器之后失效
httpOnly 講cookie標記為只有http 服務請求才能訪問
maxAge : 以毫秒為單位的過期時間,比expire GMT更靈活
path cookie 的路徑
secure 標記只有在https 協議下才能請求
signed 表示是否對 cookie 簽名

repsones.send() 發送http 響應

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/919205.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/919205.shtml
英文地址,請注明出處:http://en.pswp.cn/news/919205.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Python 數據可視化:柱狀圖/熱力圖繪制實例解析

Python 數據可視化:柱狀圖繪制實例解析 一、引言 數據可視化是數據分析中至關重要的環節,它能將復雜的數據以直觀的圖形方式呈現,幫助我們更好地理解數據特征和規律。Python 擁有豐富的可視化庫,其中 Matplotlib 是最常用的基礎庫…

API生命周期10階段

一、策略規劃(Strategy Planning) 核心任務:業務價值對齊、技術路線設計關鍵產出: API產品藍圖:定義業務領域邊界(如支付API域、用戶API域)治理規范:《API安全標準》《版本管理策略》…

UGUI源碼剖析(9):布局的實現——LayoutGroup的算法與實踐

UGUI源碼剖析(第九章):布局的實現——LayoutGroup的算法與實踐 在前一章中,我們剖析了LayoutRebuilder是如何調度布局重建的。現在,我們將深入到布局核心,去看看那些具體的組件——LayoutGroup系列組件是如…

GitHub PR 提交流程

step1 在 GitHub 上 fork 目標倉庫&#xff08;手動操作&#xff09; step2 將 fork 的目標倉庫克隆到本地 git clone https://github.com/<your-username>/<repo-name>.git cd <repo-name>step3 與上游目標倉庫建立鏈接 git remote add upstream https://gi…

礦物分類案列 (一)六種方法對數據的填充

目錄 礦物數據項目介紹&#xff1a; 數據問題與處理方案&#xff1a; 數據填充策略討論&#xff1a; 模型選擇與任務類型&#xff1a; 模型訓練計劃&#xff1a; 一.數據集填充 1.讀取數據 2.把標簽轉化為數值 3.把異常數據轉化為nan 4.數據Z標準化 5.劃分訓練集測試…

vue:vue3的方法torefs和方法toref

在 Vue 3 的 Composition API 中,toRef 和 toRefs 是兩個用于處理響應式數據的重要工具,它們專門用于從 reactive() 對象中提取屬性并保持響應性。 toRef() 作用:將 reactive 對象的單個屬性轉換為一個 ref 對象,保持與源屬性的響應式連接。 使用場景: 需要單獨提取 rea…

Android 移動端 UI 設計:前端常用設計原則總結

在 Android 移動端開發中&#xff0c;優秀的 UI 設計不僅需要視覺上的美觀&#xff0c;更需要符合用戶習慣、提升操作效率的設計邏輯。前端 UI 設計原則是指導開發者將功能需求轉化為優質用戶體驗的核心準則&#xff0c;這些原則貫穿于布局結構、交互反饋、視覺呈現等各個環節。…

計算機網絡 TCP三次握手、四次揮手超詳細流程【報文交換、狀態變化】

TCP&#xff08;傳輸控制協議&#xff09;是互聯網最重要的協議之一&#xff0c;它保證了數據的可靠、有序傳輸。連接建立時的“三次握手”和連接關閉時的“四次揮手”是其核心機制&#xff0c;涉及特定的報文交換和狀態變化。 一、TCP 三次握手&#xff08;Three-Way Handshak…

使用Applications Manager進行 Apache Solr 監控

Apache Solr 為一些對性能極為敏感的環境提供搜索支持&#xff1a;電子商務、企業應用、內容門戶和內部知識系統。因此&#xff0c;當出現延遲增加或結果不一致的情況時&#xff0c;用戶會立刻察覺。而當這些問題未被發現時&#xff0c;情況會迅速惡化。 Apache Solr 基于 Apa…

Shell腳本-for循環語法結構

一、前言在 Linux Shell 腳本編程中&#xff0c;for 循環 是最常用的控制結構之一&#xff0c;用于重復執行一段命令&#xff0c;特別適用于處理列表、文件、數字序列等場景。本文將詳細介紹 Shell 腳本中 for 循環的各種語法結構&#xff0c;包括&#xff1a;? 經典 for in 結…

記SpringBoot3.x + Thymeleaf 項目實現(MVC架構模式)

目錄 前言 一、創建SpringBoot項目 1. 創建項目 2. 運行項目 二、連接數據庫實現登錄 1. pom.xml文件引入依賴包 2. application.yml文件配置 3. 數據持久層&#xff0c;mybatis操作映射 4. Service接口及實現 5. Controller代碼 6. Thymeleaf頁面登錄 7. 運行項目…

Java 導出word 實現表格內插入圖表(柱狀圖、折線圖、餅狀圖)--可編輯數據

表格內插入圖表導出效果表格內圖表生成流程分析 核心問題與解決方案 問題 Word 圖表作為獨立對象&#xff0c;容易與文本分離位置難以精確控制&#xff0c;編輯時容易偏移缺乏與表格數據的關聯性 解決方案 直接嵌入&#xff1a;將圖表嵌入表格單元格&#xff0c;確保數據關聯精…

北京JAVA基礎面試30天打卡12

1.MySQL中count(*)、count(I)和count(字段名)有什么區別&#xff1f; 1**.COUNT ()**是效率最高的統計方式&#xff1a;COUNT()被優化為常量&#xff0c;直接統計表的所有記錄數&#xff0c;不依賴字段內容&#xff0c;開銷最低。推薦在統計整個表的記錄數時使用。 2.**COUNT(1…

【AI】——結合Ollama、Open WebUI和Docker本地部署可視化AI大語言模型

&#x1f3bc;個人主頁&#xff1a;【Y小夜】 &#x1f60e;作者簡介&#xff1a;一位雙非學校的大三學生&#xff0c;編程愛好者&#xff0c; 專注于基礎和實戰分享&#xff0c;歡迎私信咨詢&#xff01; &#x1f386;入門專欄&#xff1a;&#x1f387;【MySQL&#xff0…

RAG學習(二)

構建索引 一、向量嵌入 向量嵌入&#xff08;Embedding&#xff09;是一種將真實世界中復雜、高維的數據對象&#xff08;如文本、圖像、音頻、視頻等&#xff09;轉換為數學上易于處理的、低維、稠密的連續數值向量的技術。 想象一下&#xff0c;我們將每一個詞、每一段話、…

亞馬遜店鋪績效巡檢_影刀RPA源碼解讀

一、項目簡介 本項目是一個基于RPA開發的店鋪績效巡店機器人。該機器人能夠自動化地登錄賣家后臺&#xff0c;遍歷多個店鋪和站點&#xff0c;收集并分析各類績效數據&#xff0c;包括政策合規性、客戶服務績效、配送績效等關鍵指標&#xff0c;并將數據整理到Excel報告中&…

跨越南北的養老對話:為培養“銀發中國”人才注入新動能

2025年8月16日&#xff0c;北京養老行業協會常務副會長陳楫寶一行到訪廣州市白云區粵榮職業培訓學校&#xff0c;受到頤年集團副總李娜的熱情接待。此次訪問不僅是京穗兩地養老行業的一次深度交流&#xff0c;更為推動全國智慧養老體系建設、提升養老服務專業化水平注入了新動能…

Spring IOC 學習筆記

1. 概述Spring IOC&#xff08;Inversion of Control&#xff0c;控制反轉&#xff09;是一種設計思想&#xff0c;通過依賴注入&#xff08;Dependency Injection&#xff0c;DI&#xff09;實現。它的核心思想是將對象的創建和依賴關系的管理交給Spring容器&#xff0c;從而降…

揭開Android Vulkan渲染封印:幀率暴增的底層指令

ps&#xff1a;本文內容較干&#xff0c;建議收藏后反復邊跟進源碼邊思考設計思想。壹渲染管線的基礎架構為什么叫渲染管線&#xff1f;這里是因為整個渲染的過程涉及多道工序&#xff0c;像管道里的流水線一樣&#xff0c;一道一道的處理數據的過程&#xff0c;所以使用渲染管…

HTTP 請求轉發與重定向詳解及其應用(含 Java 示例)

在 Web 開發中&#xff0c;我們經常需要在不同頁面之間跳轉&#xff0c;比如登錄成功后跳到首頁、提交表單后跳到結果頁面。這時&#xff0c;常見的兩種跳轉方式就是 請求轉發&#xff08;Request Forward&#xff09; 和 重定向&#xff08;Redirect&#xff09;。雖然它們都能…