Req.body is empty object - javascript

I dont know why did? Help me debug! Please
i try console.log(req.body) and i get {} (empty object)
I tried many ways but I still couldn't understand why.
I tried using middleware but it didn't work either
const express = require("express");
const app = express();
const pug = require('pug');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('view engine' , 'pug');
app.set('views', './views');
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('./db.json')
const db = low(adapter)
app.get('/todos/create', (req, res)=> {
res.render('create');
});
app.post('/todos/create', (req,res)=> {
console.log(req.body);
db.get('todos').push(req.body).write();
res.redirect('/todos');
});
app.listen(3000);```
this is file create.bug
```h1 Create New List
form(action="/todos/create", method="post", enctype="multipart/form-data")
.form-group
label(for="id") Id
input#id(name="id" type="text")
.form-group
label(for="text") Text
input#text(name="text" type="text")
button Create```
----------

The body-parser module is responsible for parsing data ; you use it in your code, but I don't even see where you import it. You need at least to import it at the top of your file
var bodyParser = require('body-parser')
See others example of use here : https://www.npmjs.com/package/body-parser

Related

express.js get method cannot get req.body value

I use vue3, vuex, express.js and mysql. In the below router get method, I call "console.log(req.body)" and shows "[object Object]", and I call "console.log(req.body.userid)" and shows "undefined".
router.get('/',async function(req,res){
const userId = req.body.userid;
console.log("req body is: "+req.body);
console.log("req.body.userid is: "+req.body.userid);
.....
}
In the below method, I pass userid value as a json object. I call "console.log("post userid: "+userinfo.userid);" and shows the the right value "1";
async getsp(){
var userinfo = JSON.parse(localStorage.getItem('user'));
console.log("post userid: "+userinfo.userid);
var userid = userinfo.userid;
var obj = {userid};
return await axios.get('//localhost:8081/getSp',obj)
.then(...)
},
And in the main router file I used body-parser, the file context is below:
require("dotenv").config();
const express = require('express');
const bodyParser = require('body-parser');
var cors = require('cors');
const signup = require('./userSignUp');
const login = require('./userLogin');
const createEvsp = require('./createEvsp');
const getSp = require('./getSp');
//const createFile = require('./createFile');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(cors())
app.use(express.json());
app.use(
express.urlencoded({
extended: true
})
);
app.use("/signup",signup);
app.use("/dologin",login);
app.use("/createEvsp",createEvsp);
app.use("/getSp",getSp);
//app.use("/createFile",createFile);
app.listen(8081,function () {
console.log('Server running at 8081 port');
});
The problem was an HTTP method understanding and how express works
To solve it it was needed to use the express middleware /:userid for accessing to the parameter using req.params.userid
According to the http standards for sending the data we generally use POST request.
There is a good answer in stack here Information about Get HTTP Request
Sayf-Eddine

expressjs display post data returns an empty object

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

Node JS Middleware Function Required

When I run the following:
const express = require('express');
const bodyParser = require('body-parser');
const routes = require("./routes.js");
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(routes);
var port = process.env.PORT || 3000;
app.listen(port);
I get:
TypeError: app.use() requires a middleware function.
The console says the error occurs at the u in app.use(routes);. However if I run:
var express = require('express');
var bodyParser = require('body-parser');
var clientSessions = require('client-sessions');
var routes = require("./routes");
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/', express.static('./'));
app.use('/js', express.static('./public/js'));
app.use('/CSS', express.static('./public/CSS'));
app.use('/images', express.static('./public/images'));
app.use('/views', express.static('./public/views'));
app.use(clientSessions({
secret: 'ugkgdiuwgbkbgjwjkgvo'
}));
app.use(routes);
var port = process.env.PORT || 3000;
app.listen(port);
From a different project, that project works fine which leads me to believe there is something wrong with my current project.
However I cannot figure out what. I've tried looking at several other problems similar to mine but none of their solutions helped. Thanks in advance!
routes.js (following a request by #31piy):
var express = require("express");
var router = express.Router();
router.get("/signup",function(request,response){
response.sendFile(__dirname + "/Client/HTML/signup.html");
});
router.post("/signup",function(request,response){
});
router.get("/login",function(request,response){
response.sendFile(__dirname + "/Client/HTML/login.html");
});
You need to export the “router” from routes.js in order for it to work.
In your case add this line at the end of routes.js
module.exports = router;
That way app.use would be using an actual instance of router.
If you make a router function in different js file
It is needed to be exported so that your app.js can use it.
module.exports=router
This will help

Express.js POST method doesn't work

I'm trying to make a discussion-based Node.js/Express-app and I'm working on the page to create a discussion. I was just testing if my discussion controller file was linked, but everytime I click the button to POST my form, it doesn't do anything.
my pug (view), called 'createDisc.pug'
extends layout
block content
h1 Create new discussion
form(action='', method='post')
div
label(for='title') Title
input#title
div
label(for='desc') Description
input#desc
div
input(type='submit', value='Create')
my router, called 'createDisc.js'
var express = require('express');
var router = express.Router();
var disc = require('../controllers/disc');
router.get('/discussion/create', function (req, res, next) {
res.render('createDisc');
});
router.post('/discussion/create', disc.createDisc);
module.exports = router;
my controller called 'disc.js' where I'm just trying to send 'test' to my console
exports.createDisc = function (req, res, next) {
console.log('test');
};
my app.js file
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const passport = require('passport');
const path = require('path');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const app = express();
const db = require('./controllers/db');
require('./config/passport')(passport);
mongoose.connect(db.url);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use('/', require('./routes/createDisc'));
app.listen(3000, function() {
console.log('Example listening on port 3000!')
})
You mentioned /discussion/create as your GET route and linking it to the express router like:
router.get('/discussion/create', function (req, res, next) {
res.render('createDisc');
});
router.route('/discussion/create', disc.createDisc);
So in reality, you are enabling the route something like:
GET /discussion/create/discussion/create
Please try with .post() hook and use it like:
router.post('/', function (req, res, next) {
res.render('createDisc');
});
router.route('/discussion', disc.createDisc);
Reference: http://expressjs.com/en/guide/routing.html
Tip: Please refer to this link for making more meaningful routes. https://github.com/squareboat/api-guidelines#http-methods
Update #1
Currently, in your HTML(pug) form, you have action='', this means your form is making request to POST /.
Please change the action value to action='/discussion/create' and try again.
Update #2
I have made a trimmed down version of your code(without view or db), and it's working perfectly. you can see code here.
Routes to test are:
GET http://localhost:3000/discussion/create
POST http://localhost:3000/discussion/create
Update #3
In your pug file, your indentation is wrong because of which the input fields are not enclosed inside the form tag. You had an empty form.
extends layout
block content
h1 Create new discussion
form(action='/discussion/create', method='post')
div
label(for='title') Title
input#title
div
label(for='desc') Description
input#desc
div
input(type='submit', value='Create')
This will work.
Try to modify the form to be like this :
form(method='post', action='./create')
And see if it works

express4.2.0 session is undefined

I am finding a trouble to set a session with node.js using express4.2.0 I show you my code and after I comment:
APP.js
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var cookieSession = require('cookie-session');
var mainModel = require('./model/main_model');
var users = require('./routes/users');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieSession({
keys: ['secret1', 'secret2']
}));
app.use('/users', users);
/*Evething that express makes automatically*/
app.listen(8080);
USERS.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res)
{
if(req.cookie && req.cookie.user) res.send("COOKIE");
else if(req.session && req.session.user) res.send("SESSION");
else res.render('users/new_user', {title:"NEW USER"});
});
/*there is more content... but not relevant. */
function makeTheUserSession(result, res)
{
result['go'] = '/users';
//res.session.user = result.result[0];
//res.cookie('user', result.result[0]);
res.send(result);
}
The function makeTheUserSession is call from the method post of '/users' (to find a users on the data base).
If I uncomment the res.session.user line, when I invoque makeTheUserSession the app breaks, stop, capito, dead (Cannot set property 'user' of undefined)...
If I uncomment the res.cookie('user', result... line, when I invke the function, and after I see the browser cookies on the settings I found a cookie called user with the values of result.result[0]... but after on the get method it doesn´t works how I expect... res never sends me "COOKIE".
I had sawn the same question many times repeated, but I didn´t see a answer that worth for me: some ones talk about connect middleware (I am using express), other say to use "app.use(express.session(keyword)) but it only works with the old version of express. The express-session module is deprecated, and I would want to use a more actuallity middleware.
I hope your answers. Thank you very much.
It's req.session not res.session, fix that and you should be good to go.

Categories

Resources