簡體   English   中英

使用 Node.js 和 Express POST 時如何訪問請求正文?

[英]How to access the request body when POSTing using Node.js and Express?

我有以下 Node.js 代碼:

var express = require('express');
var app = express.createServer(express.logger());
app.use(express.bodyParser());

app.post('/', function(request, response) {
    response.write(request.body.user);
    response.end();
});

現在,如果我發布類似的內容:

curl -d user=Someone -H Accept:application/json --url http://localhost:5000

我得到Someone預期。 現在,如果我想獲得完整的請求正文怎么辦? 我嘗試做response.write(request.body)但 Node.js 拋出一個異常說“第一個參數必須是字符串或緩沖區”然后進入一個“無限循環”,一個異常說“不能在它們之后設置標頭發送。 ”; 即使我做了var reqBody = request.body;這也是正確的var reqBody = request.body; 然后寫response.write(reqBody)

這里有什么問題?

另外,我可以在不使用express.bodyParser()情況下獲取原始請求嗎?

express v4.16開始不需要任何額外的模塊,只需使用內置的JSON 中間件

app.use(express.json())

像這樣:

const express = require('express')

app.use(express.json())    // <==== parse request body as JSON

app.listen(8080)

app.post('/test', (req, res) => {
  res.json({requestBody: req.body})  // <==== req.body will be a parsed JSON object
})

注意 - 所依賴的body-parser已經包含在 express 中。

也不要忘記發送標題Content-Type: application/json

Express 4.0及以上:

$ npm install --save body-parser

然后在您的節點應用程序中:

const bodyParser = require('body-parser');
app.use(bodyParser);

Express 3.0 及以下:

嘗試在您的 cURL 調用中傳遞它:

--header "Content-Type: application/json"

並確保您的數據采用 JSON 格式:

{"user":"someone"}

此外,您可以在 node.js 代碼中使用 console.dir 來查看對象內的數據,如下例所示:

var express = require('express');
var app = express.createServer();

app.use(express.bodyParser());

app.post('/', function(req, res){
    console.dir(req.body);
    res.send("test");
}); 

app.listen(3000);

另一個問題可能也有幫助: How to receive JSON in express node.js POST request?

如果您不想使用 bodyParser,請查看其他問題: https ://stackoverflow.com/a/9920700/446681

從 Express 4 開始,以下代碼似乎可以解決問題。 請注意,您需要使用npm安裝body-parser

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));


app.listen(8888);

app.post('/update', function(req, res) {
    console.log(req.body); // the posted data
});

對於 2019 年,您不需要安裝body-parser

您可以使用:

var express = require('express');
var app = express();
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.listen(8888);
app.post('/update', function(req, res) {
    console.log(req.body); // the posted data
});
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())

var port = 9000;

app.post('/post/data', function(req, res) {
    console.log('receiving data...');
    console.log('body is ',req.body);
    res.send(req.body);
});

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

這會幫助你。 我假設你在 json 中發送 body。

你不應該使用body-parser它已被棄用。 試試這個

 const express = require('express') const app = express() app.use(express.json()) //Notice express.json middleware

app.use()函數用於在指定的路徑上掛載指定的中間件函數。 它主要用於為您的應用程序設置中間件。

現在要訪問身體只需執行以下操作

 app.post('/', (req, res) => { console.log(req.body) })

這也可以在不依賴body-parser情況下實現,監聽request:datarequest:end並在request:end返回響應,參考下面的代碼示例。 參考: https : //nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body

var express = require('express');
var app = express.createServer(express.logger());

app.post('/', function(request, response) {

    // push the data to body
    var body = [];
    request.on('data', (chunk) => {
      body.push(chunk);
    }).on('end', () => {
      // on end of data, perform necessary action
      body = Buffer.concat(body).toString();
      response.write(request.body.user);
      response.end();
    });
});

就我而言,我缺少設置標題

"Content-Type: application/json"

嘗試這個:

response.write(JSON.stringify(request.body));

這將獲取bodyParser為您創建的對象並將其bodyParser回字符串並將其寫入響應。 如果您想要確切的請求正文(具有相同的空格等),您將需要在請求之前附加dataend偵聽器並逐塊構建字符串,如您在來自 connectjson 解析源代碼中所見。

如果你懶得閱讀大量的帖子數據。 您可以簡單地粘貼以下幾行來讀取 json。

下面是 TypeScript 的類似也可以用於 JS。

應用程序

 import bodyParser from "body-parser";
 // support application/json type post data
 this.app.use(bodyParser.json());
 // support application/x-www-form-urlencoded post data
 this.app.use(bodyParser.urlencoded({ extended: false }));

在您接收 POST 調用的任何控制器之一中,如下所示

用戶控制器.ts

 public async POSTUser(_req: Request, _res: Response) {
   try {
          const onRecord = <UserModel>_req.body;
           /* Your business logic */
           _res.status(201).send("User Created");
        }
    else{
           _res.status(500).send("Server error");
           }        
   };

_req.body 應該將您的 json 數據解析為您的 TS 模型。

我對 JS 和 ES 完全陌生,但似乎對我有用的是:

JSON.stringify(req.body)

讓我知道它是否有任何問題!

您聲稱“嘗試做的”正是您在代碼中編寫的內容,當您使用 curl 調用它時“按預期”工作。

您收到的錯誤似乎與您向我們展示的任何代碼無關。

如果您想獲取原始請求, request根據dataend事件的請求設置處理程序(當然,刪除對express.bodyParser()任何調用)。 請注意, data事件將分塊發生,除非您為data事件設置編碼,否則這些塊將是緩沖區,而不是字符串。

通過以下命令安裝 Body Parser

$ npm install --save body-parser

配置正文解析器

const bodyParser = require('body-parser');
app.use(bodyParser);
app.use(bodyParser.json()); //Make sure u have added this line
app.use(bodyParser.urlencoded({ extended: false }));

接受的答案僅適用於與 JSON 格式兼容的正文。 通常,可以使用訪問主體

app.use(
  Express.raw({
    inflate: true,
    limit: '50mb',
    type: () => true, // this matches all content types
  })
);

喜歡張貼在這里 req.body有一個Buffer類型,可以轉換成想要的格式。

例如通過以下方式轉換為字符串:

let body = req.body.toString()

或通過以下方式進入 JSON:

let body = req.body.toJSON();

您可以使用以下代碼來記錄帖子數據:

router.post("/users",function(req,res){
    res.send(JSON.stringify(req.body, null, 4));
});

暫無
暫無

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

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