Post body empty despite setting extended to true - javascript

I'm trying to make a form that submits data, but the data when handled using express in the app.js file returns an empty array.
App.JS:
const mongoose = require('mongoose');
const express = require('express')
const path = require('path')
const Person = require('./models/Person')
const bodyParser = require('body-parser')
const app = express()
app.use(express.static(path.join(__dirname, 'public')))
app.use(bodyParser.urlencoded({ extended: true }))
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.post('/post', (req, res) => {
const newInfo = req.body
console.log("Logging new data")
console.log(newInfo.emailAddress)
res.render('post')
})

Related

hbs.express4 is not a function

I was doing a nodejs based project using express and when I was adding partials to the server.js file. I got a type error: TypeError: hbs is not a function. I installed npm express-handlebars But still the same error
const express = require('express')
const http = require('http')
const path = require('path')
const hbs = require('express-handlebars')
const socket = require('socket.io')
const router = require('./routes/routes.js')
const app = express()
const server = http.createServer(app)
const session = require('express-session')
app.engine('hbs', hbs.express4({
defaultLayout: path.join(__dirname, 'views', 'layouts', 'default')
}))
app.use(express.json())
app.set('view engine', 'hbs')
app.use(express.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'public')))
app.use('/', require('./routes/home'))
app.set('views', path.join(__dirname, 'views'))
server.listen(PORT, () => { console.log(`Server is running at http://localhost:${server.address().port}`) })

Express: Unable to route

On my home page i have a student login button. On clicking i want to redirect to a login page. But i am not getting request inside login route.
server.js file
const express=require('express');
const path=require('path');
const bodyparser=require('body-parser');
const session=require('express-session');
const{v4:uuidv4}=require('uuid');
const router=require('./router');
const app=express();
const port=process.env.PORT||3000;
app.arguments(bodyparser.json())
app.arguments(bodyparser.urlencoded({extended:true}))
app.set('view engine','ejs');
app.arguments(session({
secret:uuidv4(),
resave: false,
saveUninitialized: true
}));
app.use('/route',router)
//home route
app.get('/',(req,res)=>{
res.render('home');
})
app.listen(port,()=>{console.log("Listening to the server on http://localhost:3000")});
router.js file
var express=require('express');
var router=express.Router();
//student login page
router.get("/studentlogin",(req,res)=>{
res.end("Login Successfull");
})
Module.exports=router;
views/home.ejs file
<form action="/route/studentlogin">
<input type="submit" class="btn btn-outline-primary align-items-end" value="Student Login">
</form>
What i am expecting is to print login successfull but i am getting error.
Error
Cannot GET /route/studentlogin
Try to use app.use instead of app.arguments
Replace bodyParser with express
Add the cors library to enable CORS
Export a module using module.exports
Server.js
const express = require('express');
const path = require('path');
const cors = require('cors')
const session = require('express-session');
const { v4: uuidv4 } = require('uuid');
const router = require('./router');
const app = express();
const port = process.env.PORT || 3000;
app.use(cors())
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.use(
session({
secret: uuidv4(),
resave: false,
saveUninitialized: true,
})
);
app.use('/route', router);
//home route
app.get('/', (req, res) => {
res.render('home');
});
app.listen(port, () => {
console.log('Listening to the server on http://localhost:3000');
});
router.js
...
module.exports=router;

Express does not show request body on form data on using body parser and multer

In Index.js I have added bodyparser and bodyparser url encoder as middleware.
const bodyParser = require("body-parser");
require("dotenv").config();
const PORT = process.env.PORT || 3032;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
In other file I have just console logged the request body and it logs out an empty object.
webhooks.post("/webhooks/", async (req, res) => {
console.log(req.body);
res.send("ok");
});
the res.body is still {}

I get the error that the body is not defined in expres?

express js the body undefined error
I shared the files below. I got very angry. No error appears. Please help me.
Although I do it again I get the same error
I searched a lot but none of the solutions worked.
main.js
const express = require('express')
const router = express.Router()
router.get('/', (req,res)=>{
res.render('site/index')
})
router.get('/login', (req,res)=>{
res.render('site/login')
})
router.get('/register', (req,res)=>{
res.render('site/register')
})
router.get('/postcreate', (req,res)=>{
res.render('site/postcreatepage')
})
router.get('/postupdate', (req,res)=>{
res.render('site/postupdatepage')
})
router.post('/post/post', (req,res)=>{
console.log(req.body)
})
module.exports = router
I checked and searched many times could not solve
app.js
const express = require('express')
const path = require('path')
const app = express()
const port= 3000
const hostname = '127.0.0.1'
const mongoose = require('mongoose')
const main = require('./routes/main')
var bodyParser = require('body-parser');
app.use('/', main)
app.use(express.static('static'))
mongoose.connect('mongodb://127.0.0.1/nodemon_db',{
useNewUrlParser: true,
useUnifiedTopology:true
})
app.engine('handlebars', require('exphbs'))
app.set('view engine','handlebars')
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.listen(port, hostname, ()=> console.log(`Example app listening on port http://${hostname}:${port}/`))
Although I do it again I get the same error
html
<html>
<head>
</head>
<body>
<form action="post/post" method="post">
<input name="title"><br>
<input name="content"><br>
<button type="submit">But</button>
</form>
</body>
</html>
In your route, you have to return a response other wise the request will hang:
main.js
router.post('/post/post', (req,res)=>{
console.log(req.body)
const resObject = {
... do something with req.body ...
};
return res.status(201).json(resObject);
});
In your app entrypoint, set your routes after your config and middleware:
app.js
const express = require('express')
const path = require('path')
const app = express()
const port= 3000
const hostname = '127.0.0.1'
const mongoose = require('mongoose')
const main = require('./routes/main')
var bodyParser = require('body-parser');
/* config */
mongoose.connect('mongodb://127.0.0.1/nodemon_db',{
useNewUrlParser: true,
useUnifiedTopology:true
})
/* Middleware */
app.use(express.static('static'))
app.engine('handlebars', require('exphbs'))
app.set('view engine','handlebars')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
/* Routes */
app.use('/', main)
app.listen(port, hostname, () => console.log(`Example app listening on port http://${hostname}:${port}/`)

Body parser's req.body keeps returning undefined

The Content-Type of the header is set to application/JSON this way, I believe. My input fields are enveloped in a <form method="POST"> with a type="submit" input field inside. Why do I get undefined for the body then? What's an alternative module to the body parser?
var express = require('express'),
app = require('express')(),
cookieSession = require('cookie-session'),
ejs = require('ejs'),
path = require('path'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
auth = require('./middleware/auth.js'),
user = require('./models/user.js'),
router = express.Router();
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', function (req, res) {
//returns undefined
console.log(req.body);
user.create(req.session.username, req.session.email, req.session.password);
res.render('./game/game.html', {});
});
app.get('/', function (req, res) {
res.render('./index.html', {});
});
app.get('/game', function (req, res) {
res.render('/views/index.html');
});
//expose router constructor
module.exports = router;
app.listen(3000);

Categories

Resources