解析 Node 中的請求正文
在之前的簡單程式碼示例中,我們瞭解瞭如何路由請求以及建立檔案以輸入測試資料。
現在,我們需要將使用者輸入的輸入資料儲存到文字檔案中。
Node.js 如何處理傳入的請求資料
Node.js 以片段的形式讀取資料,這意味著它使用流來讀取資料。一旦 Node 完成了讀取請求資料的操作,我們就可以繼續使用該資料來實現我們的目的。
First read data in chunks const requestBody = []; req.on(‘data’, (chunks)=>{ requestBody.push(chunks); });
我們註冊了對傳入 http 請求的“data”事件。此事件將繼續傳輸流資料並將其推送到 requestBody 常量變數中。
Append the whole request data Once data is completed, we will convert the received data to string with ‘end ’ event req.on(‘end’, ()=>{ const parsedData = Buffer.concat(requestBody).toString(); });
我們以鍵值對的形式獲取請求引數。我們需要對它進行拆分才能將值儲存在文字檔案中。
const username = parsedData.split(‘=’)[1];
完整的 App.js 檔案及儲存使用者輸入名稱的程式碼如下 −
const http = require('http'); const fs = require('fs'); const server = http.createServer((req, res)=>{ const url = req.url; if(url === '/'){ res.write('<html>'); res.write('<head> <title> Hello TutorialsPoint </title> </head>'); res.write(' <body> <form action="/username" method="POST"> <input type="text" name="username"/> <button type="submit">Submit</button> </body>'); res.write('</html>'); return res.end(); } if(url === '/username' && req.method === 'POST'){ const requestBody = []; req.on('data', (chunks)=>{ requestBody.push(chunks); }); req.on('end', ()=>{ const parsedData = Buffer.concat(requestBody).toString(); const username = parsedData.split('=')[1]; fs.writeFileSync('username.txt', username); }); //redirect res.statusCode=302; res.setHeader('Location','/'); return res.end(); } res.write('<html>'); res.write('<head> <title> Hello TutorialsPoint </title> </head>'); res.write(' <body> Hello </body>'); res.write('</html>'); res.end(); }); server.listen(3000); Note that we wrote file write operation inside end event : req.on('end', ()=>{ const parsedData = Buffer.concat(requestBody).toString(); const username = parsedData.split('=')[1]; fs.writeFileSync('username.txt', username); });
這是因為我們希望首先完成結束事件以獲取使用者名稱,然後再將它寫入檔案。
現在,這是使用核心 node.js 進行工作的背景知識,這樣可以更輕鬆地以更簡單的方式在 Express.js 中處理所有這些解析邏輯。
我們在後續的文章中將介紹 express.js 處理請求解析的方式。
廣告