Programing

Node.js 및 Express를 사용하여 POST 할 때 요청 본문에 액세스하는 방법은 무엇입니까?

crosscheck 2020. 6. 18. 21:23
반응형

Node.js 및 Express를 사용하여 POST 할 때 요청 본문에 액세스하는 방법은 무엇입니까?


다음 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();
});

이제 내가 POST를하면 :

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

나는 Someone예상대로 얻는다 . 이제 전체 요청 본문을 얻으려면 어떻게해야합니까? 시도 response.write(request.body)했지만 Node.js는 " 첫 번째 인수는 문자열 또는 버퍼 여야합니다 "라는 예외를 발생시키고 " 송신 후 헤더를 설정할 수 없습니다 "라는 예외와 함께 "무한 루프"로갑니다 . ;; 내가 var reqBody = request.body;한 다음 글을 쓰 더라도 마찬가지 response.write(reqBody)입니다.

여기서 무슨 문제가 있습니까?

또한 사용하지 않고 원시 요청을 얻을 수 express.bodyParser()있습니까?


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);

이 다른 질문도 도움이 될 수 있습니다 : express node.js POST 요청에서 JSON을받는 방법?

bodyParser를 사용하지 않으려면이 다른 질문을 확인하십시오 : https://stackoverflow.com/a/9920700/446681


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부터 다음 코드가 트릭을 수행하는 것으로 보입니다. 을 사용 body-parser하여 설치해야합니다 npm.

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
});

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);

This will help you. I assume you are sending body in json.


This can be achieved without body-parser dependency as well, listen to request:data and request:end and return the response on end of request, refer below code sample. ref: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();
    });
});

Try this:

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

That will take the object which bodyParser has created for you and turn it back into a string and write it to the response. If you want the exact request body (with the same whitespace, etc), you will need data and end listeners attached to the request before and build up the string chunk by chunk as you can see in the json parsing source code from connect.


What you claim to have "tried doing" is exactly what you wrote in the code that works "as expected" when you invoke it with curl.

The error you're getting doesn't appear to be related to any of the code you've shown us.

If you want to get the raw request, set handlers on request for the data and end events (and, of course, remove any invocations of express.bodyParser()). Note that the data events will occur in chunks, and that unless you set an encoding for the data event those chunks will be buffers, not strings.


For 2019, you don't need to install body-parser.

You can use:

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
});

If you're lazy enough to read chunks of post data. you could simply paste below lines to read json.

Below is for TypeScript similar can be done for JS as well.

app.ts

 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 }));

In one of your any controller which receives POST call use as shown below

userController.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 should be parsing you json data into your TS Model.


You use the following code to log post data:

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

참고URL : https://stackoverflow.com/questions/11625519/how-to-access-the-request-body-when-posting-using-node-js-and-express

반응형