1

I need to create express server that has 1 post endpoint which gets POST data and print it in the console where the server is started:

var express = require("express");
var app = express();

app.get("/", function (req, res) {
res.send("GET request");
});

app.post("/", function (req, res) {
console.log(req.params);
res.send("POST request");
});

app.listen(2705, function () {
console.log("Server is running on port: " + 2705);
});

enter code here

Cannot find a solution how to print this POST request in the console when for example the request is from another local server.

tabula
  • 243
  • 1
  • 4
  • 13

3 Answers3

1

You are using req.params, which is not the body of the POST. If you want to see the data that was sent with the POST you will need to access req.body. Additionally, express needs to be told to parse out the body. This can be accomplished using the Express body-parser.

This article gives more explanation on it.

Community
  • 1
  • 1
carchase
  • 493
  • 6
  • 18
1
const express = require('express');

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

const product = require('./routes/product.route'); // Imports routes for the products
const app = express();


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

// In express.js the order in which you declare middleware is very important. bodyParser middleware must be defined early than your own middleware (api endpoints).
app.use('/products', product);// if you've mentioned routers

// solution you're looking for
app.post("/", function (req, res) {
console.log(req.body);// req data
res.send("POST request!!!");
});



let port = 8001;
app.listen(port, () => {
    console.log('Server is up and running on port number ' + port);
});
Chang
  • 435
  • 1
  • 8
  • 17
0
var app = require('express')();
var bodyParser = require('body-parser');


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

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

you can find more details about this in here