0

So I'm developing a chat server using expressjs and socketio and decided to create an admin where backend built in with the node chat server itself.

const express = require("express");
const app = express();
const port = 3700;

let io = require('socket.io').listen(app.listen(port));

let socketList = io.sockets.server.eio.clients;

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

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));

app.get('/login', function(req, res) {
    res.render('login', { title: 'Login | Argos Chat' });
});

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

So upon login data submission, I tried to display the post data from the login form but it returns me an empty object {}

console.log(req.body);

Tried to do req.params but same result .Any help, ideas is greatly appreciated.

Juliver Galleto
  • 8,831
  • 27
  • 86
  • 164

3 Answers3

0

I tried running your code and its working fine. Maybe the way you are calling the API is not right

To support content-type: x-www-form-urlencoded you should use

app.use(bodyParser.urlencoded({ extended: true }));

and to support content-type: application/json you should use

app.use(bodyParser.json());

I think you are using form-data, for that neither of these will work. For that you may want to use formidable package. We should use form-data content type only when we are sending any images/file.

And body-parser has been merged with express. You can directly use this now

app.use(
  express.json(),
  express.urlencoded({ extended: false })
);
Dhruv Pahuja
  • 105
  • 1
  • 10
0

I think this might be a right solution for your problem, as everything seems to be right in your code, the error might be caused by the way you are calling the API and you are setting the headers:

https://stackoverflow.com/a/25904070/12090205

Luis Orbaiceta
  • 443
  • 4
  • 15
-1

enter image description here

const express = require("express");
const app = express();
const port = 3700;

let io = require('socket.io').listen(app.listen(port));

let socketList = io.sockets.server.eio.clients;

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

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));

app.get('/login', function(req, res) {
    res.render('login', { title: 'Login | Argos Chat' });
});

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

I checked Its Working.

Prakash Harvani
  • 1,007
  • 7
  • 18