解析 express.js 中的傳入請求
要接收 http 請求中的某些資料,可以在 url 路徑‘/add-username’中新增一個 form。
app.use('/add-username', (req, res,next)=>{
res.send('<form action="/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form>');
});要解析 http 請求,我們需要第三方庫 body-parser:這是一個必需的生產依賴項
npm install –save body-parser
express js 提供中介軟體 use 函式,以便在新增中介軟體之前包含一個 body 解析器。
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended: false}));上面顯示的 use(0 函式預設使用 next() 函式,因此 http 請求可以在沒有任何問題的情況下傳遞給下一個中介軟體。
上面的解析器可用於解析簡單的表單資料(如輸入文字等),但要解析檔案、json,我們將使用不同的解析器。
現在,解析請求比用核心 node.js 編寫程式碼更簡單。
Express.js 在 http 請求中提供一個屬性 body,該屬性將返回請求資料。
控制檯輸出:在 localhost: 3000/add-username 上
data: tutorials point
使用響應重定向請求非常容易,響應有一個 redirect 函式。
此處顯示了完整的 App.js 檔案 −
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', (req, res,next)=>{
next();
});
app.use('/add-username', (req, res,next)=>{
res.send('<form action="/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form>');
});
app.use('/post-username', (req, res, next)=>{
console.log('data: ', req.body.username);
res.redirect('/');
});
app.use('/', (req, res,next)=>{
res.send('<h1> first midleware: Hello Tutorials Point </h1>');
});
const server = http.createServer(app);
server.listen(3000);在安裝任何第三方庫後,應手動重新啟動 nodemon 以替代依靠 nodemon 自動重新啟動(該自動重新啟動可能無法正常工作),以生效新的庫。
廣告
資料結構
計算機網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP