How to create a Node server for POST requests only

I need to create a Node server only to receive POST requests. With the information in the request body, I need to create a system call. How should I do it? So far, I only have:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser);
app.post('/', function(req, res){
    console.log('POST /');
    console.dir(req.body);
});

port = 3000;
app.listen(port);
console.log('Listening at http://localhost:' + port)

However, when I make a POST request before 127.0.0.1haps000, the body is undefined.

var request = require ('request');

request.post(
    '127.0.0.1:3000',
    { form: { "user": "asdf" } },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body)
        }
    }
);
+4
source share
2 answers

You have a middleware problem. The tool express.bodyparser()is deprecated in Express 4.x. This means that you must use stand-alone middleware bodyparser.

Oddly enough, you are importing the correct middleware by following these steps:

var bodyParser = require('body-parser');

-. :

var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); 

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data

app.post('/', function (req, res) {
  console.log(req.body);
  res.json(req.body);
})
+3
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); 

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing     application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data

app.post('/', function (req, res) {
console.log(req.body);
res.json(req.body);
})

express, express.bodyParser . .

+2

Source: https://habr.com/ru/post/1598261/


All Articles