Cannot access req.body, even when using body-parser - javascript

I am trying to get my login functionality up and running, but i am unable to access the req.body object.
When i first encountered the issue, the post route was not even getting triggered (console.log was not showing at all in terminal) and the request would eventually time out. This stopped after i added this line in the body-parser initialization:
type: 'x-www-form-urlencoded',
Now, the console.log form the route appears in the terminal, but both parameters are empty.
Router.js
const express = require('express'),
router = express.Router();
router.post('/signup', function (req, res) {
console.log(req.body.name, req.body.password);
res.send('posted');
});
module.exports = router;
app.js
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
http_port = process.env.HTTP_PORT;
const http = require('http').createServer(app);
app.use(express.static(path.join(__dirname, 'public')));
app.use(
express.urlencoded({
type: 'x-www-form-urlencoded',
extended: true,
})
);
app.use(express.json());
app.use(cookieParser());
app.use(require('./backend/router'));
http.listen(process.env.PORT || http_port, () =>
console.log(`App listening on port ${http_port}`)
);
Form from index.html
<div>
<form method="POST" enctype="application/x-www-form-urlencoded">
<div class="row">
<label>Full Name</label>
<input
name="name"
type="text"
required
placeholder="Enter your name"
/>
</div>
<div class="row">
<label>Email</label>
<input
name="email"
type="email"
required
placeholder="Enter your email"
/>
</div>
<div class="row">
<label>Password</label>
<input
name="password"
type="password"
required
placeholder="Enter your password"
/>
</div>
<div class="row">
<label>Confirm Password</label>
<input
name="password_confirm"
type="password"
required
placeholder="Confirm your password"
/>
</div>
<div id="button" class="row">
<button
formmethod="POST"
formenctype="application/x-www-form-urlencoded"
type="submit"
>
Sign Up
</button>
</div>
</form>
</div>

I was not able to fix it, but i managed to find a workaroud. The info from the form is also in request.fields, so i am going to use that instead of request.body. I still would like to know why it doesn't work as normal though.

Remove type: 'x-www-form-urlencoded' in your parser and add action="http://localhost:3000/signup" to your form

Perhaps try
app.use(bodyParser.json());
instead of
app.use(express.json());

Related

What is causing the type error in my code?

I am trying to console.log the input in this sign up form but every time i fill the details and the submit the form then it shows the following error
TypeError: Cannot read properties of undefined (reading 'fName')
Kindly let me know the error in my code.
<form action="/" method="POST">
<img class="mb-4" src="images/mail.jpg" alt="" width="72" height="57">
<h1 class="h3 mb-3 fw-normal">Signup the Newsletter</h1>
<div class="form-floating">
<input type="text" name="fName" class="form-control top" placeholder="First Name">
</div>
<div class="form-floating">
<input type="text" name="lName" class="form-control middle" placeholder="Last Name">
</div>
<div class="form-floating">
<input type="email" name="email" class="form-control bottom" placeholder="name#example.com">
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
<p class="mt-5 mb-3 text-muted">Follow me</p>
</form>
// const https = require("https");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/", function(res, req){
var firstName = req.body.fName;
var middleName = req.body.lName;
var eMail = req.body.email;
console.log(firstName, middleName, eMail);
});
app.listen(3000, function() {
console.log("Server is running on Port 3000");
}); ```
I found these errors in your code, check them and it will work fine.
app.use("/public", express.static(path.join(__dirname, 'public'))); // use this for defining your public folder (and don't forget to import path module above).
app.post("/", function(req, res, next){
var firstName = req.body.fName;
var middleName = req.body.lName;
var eMail = req.body.email;
console.log(firstName, middleName, eMail);
});
Here as you can see in the callback function we get three parameters first will be the request object, second will be the response object and third is optional next object.
But in your case you are reading it from response object but it should be from request.
Thanks

express post method and body.req does not work

I am trying to get "POST" method form data from HTML form using app.post method but I can catch anything to req.body. What am I doing wrong?
My html form -
<form method="POST" action="/success.html">
<div id="input-area">
<textarea id="title" name="title" rows="1" cols="75" placeholder="Title" onkeyup="instance.tweaker()"></textarea>
<textarea rows="10" type="text" cols="75" placeholder="Description" name="description"></textarea>
<div id="calender"><input id="dater" type="date" value=""></div>
<button type="submit" value="Submit" id="buton">Add Task</button>
</div>
</form>
<script src="backend2.js" defer></script>
my js code
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.listen(3308,() =>{
console.log('My server is running');
})
const jsonParser = bodyParser.json();
//
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/success.html', urlencodedParser , function (req, res) {
console.log(req.body.title);
})
I reproduced your code without any error. To test it quickly, i send the index.html as the default route.
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const port = 3308;
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/index.html'));
});
app.post('/success.html', urlencodedParser, (req, res) => {
res.send(req.body.title);
});
app.listen(port, () => {
console.info(`server running on port ${port}`);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Upload Example</title>
</head>
<body>
<form method="POST" action="/success.html">
<div id="input-area">
<textarea
id="title"
name="title"
rows="1"
cols="75"
placeholder="Title"
onkeyup="removedForExample"
></textarea>
<textarea
rows="10"
type="text"
cols="75"
placeholder="Description"
name="description"
></textarea>
<div id="calender"><input id="dater" type="date" value="" /></div>
<button type="submit" value="Submit" id="buton">Add Task</button>
</div>
</form>
</body>
</html>
First of all, I am not sure which version of Express you are using but if you are using version 4.0 or up, you don't really need to import body-parser separately.
Also, you may re-order the code. Why don't you try like this?
const jsonParser = bodyParser.json();
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/success.html', urlencodedParser , function (req, res) {
console.log(req.body.title);
})
app.listen(3308,() =>{
console.log('My server is running');
})

How to fix Cannot PUT /blogs/:id

I am making RESTful BlogApp and PUT method is not working.I only get error saying Cannot PUT /blogs/:id. I don't see what could go wrong. Everything looks fine to me. Please let me know if you find a problem. I know this might be a bad post but it is one of my first posts. Here is what i coded:
<form action="/blogs/<%= blog._id %>?_method=PUT" method="POST" class="ui
form">
<div class="field">
<label for="blog[tittle]">Tittle</label>
<input name="blog[tittle]" type="text" value="<%=
blog.tittle %>">
</div>
<div class="field">
<label for="blog[image]">Image URL</label>
<input name="blog[image]" type="text" value="<%= blog.image
%>">
</div>
<div class="field">
<label for="blog[body]">Content</label>
<textarea name="blog[body]"><%= blog.body %></textarea>
</div>
<button type="submit" class="ui blue button">Save</button>
</form>
const express = require('express');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const mongoose = require('mongoose');
const app = express();
const port = 3000;
const mongoosePassword = 'bm9kZS1yZXN0LWJsb2c=';
mongoose.connect('mongodb://mesopotamija9:' + mongoosePassword + '#node-
rest-blog-shard-00-00-xb2tn.mongodb.net:27017,node-rest-blog-shard-00-01-
xb2tn.mongodb.net:27017,node-rest-blog-shard-00-02-
xb2tn.mongodb.net:27017/test?ssl=true&replicaSet=node-rest-blog-shard-
0&authSource=admin&retryWrites=true', {useNewUrlParser: true});
app.set('view engine', 'ejs')
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));
app.put('blogs/:id', function(req, res){
Blog.findByIdAndUpdate(req.params.id, req.body.blog, function(err,
updatedBlog){
if (err) {
res.redirect('/blogs');
console.log(err);
} else {
res.redirect('/blogs/' + req.params.id);
console.log(updatedBlog);
}
});
});

node.js express-uploadFile undefined

I'm trying to upload a .txt file with the middleware express-uploadFile. However, when I try to test it my file is undefined.
var express = require('express');
var fs = require('fs');
var bodyParser = require('body-parser');
var fileUpload = require('express-fileupload');
var app = express()
app.use(fileUpload());
app.use(bodyParser.urlencoded({ extended: false }))
app.post('/send', function(req, res){
console.log(req.files.UploadBox);
console.log(req.body.Question);
});
<form id="Izone" action="/send/" method="post" encType="multipart/form-data">
<input type="text" name="Question" id="Question" placeholder="Question" autofocus autocomplete="off"><br/><br/>
<label for="UploadBox" id="UploadBoxStyle"> Upload File </label>
<input type="file" name="UploadBox" id="UploadBox">
<input type="submit" name="send" id="send" value="send"/>
</form>
req.body.Question works fine. However, req.files gives me undefined.
I don't know if the issue is bodyParser or fileupload itselft.

getting values from a POST method in expressJS

I'm trying to register a user in my application. This is the HTML code:
<form id="registration_form" action="register" onsubmit="return validateForm();" method="post">
Username: <input type="text" id="username" name="user[name]" /><br />
Password: <input type="password" id="password" name="user[pass]" /><br />
Repeat Password: <input type="password" id="password_repeat" name="user[pass]" /><br />
Email: <input type="text" id="email" name="user[email]" /><br />
<button type="submit" value="Register">Register</button>
<div id="error_registration" style="color: red;">
</div>
</form>
What I do in the server is taking the values of name, pass and email.
var express = require('express')
, app = express.createServer(
express.logger(),
express.cookieParser(),
express.session({ secret: 'keyboard cat' })
)
, io = require('socket.io').listen(app)
, mongoose = require('mongoose')
, schemas = require('./schemas')
, Schema = mongoose.Schema;
app.listen(80);
app.configure(function(){
app.use(express.bodyParser());
});
[...]
app.post('/register', function (req, res) {
registerUser(req, function(result){
//do something
var username = req.body.username;
});
});
My question is: why username is always undefined? Am I reading it in the wrong way? How should I then?
Thanks
Your variable is user not username.
Look:
..input type="text" id="username" name="user[name]" ..
Also you can always do console.log(req.body) to see the POST vars in the terminal.

Categories

Resources