簡體   English   中英

如何在 Node 服務器上讀取以 application/x-www-form-urlencoded 格式接收的數據?

[英]How can I read the data received in application/x-www-form-urlencoded format on Node server?

我正在接收作為 POST 請求的 webhook URL 上的數據。 請注意,此請求的內容類型是application/x-www-form-urlencoded

這是一個服務器到服務器的請求。 在我的節點服務器上,我只是嘗試使用req.body.parameters讀取接收到的數據,但結果值是“未定義”

那么如何讀取數據請求數據呢? 我需要解析數據嗎? 我需要安裝任何 npm 模塊嗎? 你能寫一個解釋這個案例的代碼片段嗎?

如果您使用 Express.js 作為 Node.js Web 應用程序框架,請使用 ExpressJS body-parser

示例代碼將是這樣的。

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

// With body-parser configured, now create our route. We can grab POST 
// parameters using req.body.variable_name

// POST http://localhost:8080/api/books
// parameters sent with 
app.post('/api/books', function(req, res) {
    var book_id = req.body.id;
    var bookName = req.body.token;
    //Send the response back
    res.send(book_id + ' ' + bookName);
});

接受的答案使用 express 和 body-parser 中間件來表達。 但是,如果您只想解析發送到 Node http 服務器的 application/x-www-form-urlencoded ContentType 的有效負載,那么您可以在沒有 Express 額外膨脹的情況下完成此操作。

你提到的關鍵是http方法是POST。 因此,使用 application/x-www-form-urlencoded,參數將不會在查詢字符串中編碼。 相反,有效負載將在請求正文中發送,使用與查詢字符串相同的格式:

param=value&param2=value2 

為了在請求正文中獲取有效負載,我們可以使用 StringDecoder,它以保留編碼的多字節 UTF8 字符的方式將緩沖區對象解碼為字符串。 所以我們可以使用 on 方法將 'data' 和 'end' 事件綁定到請求對象,在我們的緩沖區中添加字符:

const StringDecoder = require('string_decoder').StringDecoder;
const http = require('http');

const httpServer = http.createServer((req, res) => {
  const decoder = new StringDecoder('utf-8');
  let buffer = '';

  req.on('data', (chunk) => {
    buffer += decoder.write(chunk);
  });

  req.on('end', () => {
    buffer += decoder.end();
    res.writeHead(200, 'OK', { 'Content-Type': 'text/plain'});
    res.write('the response:\n\n');
    res.write(buffer + '\n\n');
    res.end('End of message to browser');
  });
};

httpServer.listen(3000, () => console.log('Listening on port 3000') );

您必須使用特定的中間件告訴 express 處理 urlencoded 數據。

const express = require('express');
const app = express();

app.use(express.urlencoded({
    extended: true
}))

在您的路線上,您可以從請求正文中獲取參數:

const myFunc = (req,res) => {
   res.json(req.body);
}

如果您使用的是restify,它會是類似的:

var server = restify.createServer()
server.listen(port, () => console.log(`${server.name} listening ${server.url}`))
server.use(restify.plugins.bodyParser()) // can parse Content-type: 'application/x-www-form-urlencoded'
server.post('/your_url', your_handler_func)

Express 4.16+ 已經實現了他們自己的 body-parser 版本,所以你不需要在你的項目中添加依賴項。

app.use(express.urlencoded()); //Parse URL-encoded bodies

Express.js 中身體解析器的非棄用替代方案

如果您正在創建一個沒有 Express 或 Restify 等框架的 NodeJS 服務器,那么您可以使用 NodeJS 本機查詢字符串解析器 內容類型application/www-form-urlencoded格式與查詢字符串格式相同,因此我們可以重用該內置功能。

此外,如果您不使用框架,那么您實際上需要記住閱讀您的身體。 請求將包含方法、URL 和標頭,但不會包含正文,直到您告訴它讀取該數據。 你可以在這里閱讀: https : //nodejs.org/dist/latest/docs/api/http.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM