reading html file input and sending to node.js for processing - javascript

I'm using node.js for a basic form-processing task.
The html file loads, but when I submit the form, it fails to process.
Here is the code I'm running right now:
formhandling2.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendfile('peanuts.html');
app.post('/myaction', function(req, res){
var userName = req.body.userName;
res.send ('Hello: ' + userName + '.<br>' + 'Try again.');
res.sendfile('peanuts.html');
});
app.listen(80);
peanuts.html
<html>
<head>
<title>Forms></title>
</head>
<body>
form action="/myaction" method="post">
<p>Enter your name:</p>
<input type="text" name="userName" placeholder="..." />
<br>
<button type="submit">Submit</button>
</body>
</html>

You have a syntax error in your server file
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendfile('peanuts.html');
})
app.post('/myaction', function(req, res){
var userName = req.body.userName;
res.send ('Hello: ' + userName + '.<br>' + 'Try again.');
res.sendfile('peanuts.html');
});
app.listen(80);
See above, after res.sendfile('peanuts.html') you have to close }) braces.
then you have html syntax error you have not started form tag. Correct code below
<html>
<head>
<title>Forms></title>
</head>
<body>
<form action="/myaction" method="post">
<p>Enter your name:</p>
<input type="text" name="userName" placeholder="..." />
<br>
<button type="submit">Submit</button>
</body>
</html>
everything else works nice i tested once fixed

Related

Why does req.body return an empty object in console in POST request?

In my code below, the middleware is supposed to return the parsed data in console as an object accessed by req.body, but it returns an empty object for some reason.
Code and Console Snapshot1
Code and Console Snapshot2
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const { use } = require('express/lib/application');
/*
ulrEncodedParser middleware is used to invoke below function
to parse posted data to POST functions
var urlEncodedParser = bodyParser.urlencoded({extended : false});
var jsonParser = bodyParser.json();
*/
//set view engine to be able to visit views
app.set('view engine', 'ejs');
//middleware for styles to be loaded on pages when req made by views
app.use('/stylesheets', express.static('stylesheets'));
// middleware to parse application/x-www-form-urlencoded
//app.use(bodyParser.urlencoded({ extended: false }));
// middleware to parse application/json
//app.use(bodyParser.json());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
//GET "/" req, fires up home page
app.get('/', function(req, res){
res.render('home');
});
//GET "/home" req, aslo fires up home page
app.get('/home', function(req, res){
res.render('home');
});
//GET "/signup" req, fires up sign up page
app.get('/signup', function(req, res){
res.render('signup');
});
//POST information enetered on sign up form
app.post('/signup', function(req, res){
console.log(req.body);
//res.render('signup-success', req.body);
});
//server to run on port 3000
app.listen(3000, function(){
console.log('server listening on port 3000');
});
I also tried initialize two separate variables where the functions of urlencoded() and bodyParser.json() can be accessed var for both middlewares instead of using app.use() middleware this way:
var urlEncodedParser = bodyParser.urlencoded({extended : false});
var jsonParser = bodyParser.json();
and then pass in each in the app.post() request routed to the signup page but it still returns the same, empty.
Here is my signup.ejs as well for reference.
<!DOCTYPE html>
<html>
<head>
<link href="/stylesheets/style.css" rel="stylesheet" type="text/css" />
<title>Sign Up Page</title>
</head>
<body>
<h1>Sign Up</h1>
<h3>Enter the requested information below for your user profile to be created.</h3><br>
<form id="signup-form" action="/signup" method="post">
<label for="firstName">First Name</label><br>
<input type="text" id="firstName" placeholder="first name"><br><br>
<label for="musicPreferences">Music Prefrences</label><br>
<input type="text" id="musicPrefrence" placeholder="music preferences"><br><br>
<label for="favoriteArtists">Favorite Artists</label<br>
<input type="text" id="favoriteArtists" placeholder="favorite artists"><br><br>
<label for="pastConcerts">Past Concerts Attended</label><br>
<input type="text" id="pastConcerts" placeholder="concerts attended"><br><br>
<label for="futureConcerts">Fututre Concerts Want to Attend</label><br>
<input type="text" id="futureConcerts" placeholder="future concerts"><br><br>
<input type="submit" value="submit"><br>
<%- include('partials/nav.ejs') %>
</form>
</body>
</html>
Sign up Page UI
Any help is appreciated!
The backend works correctly because when sending a request with curl, body is shown in the console. It seems the client sends the request incorrectly.
screenshot

Express.js req.body is undefined

edit:guys I'm genually new to all of this. here's the html form I used. should i update this question with something else?
<form action="/pesquisar" method="post">
<input type="text" id="cO">
<input type="text" id="cD">
<input type="submit">
</form>
I'm currently trying to design a simple browser app utilizing express. console.log(req.body) comes back {} and i cant find the solution, been here for the best part of the day lol
Here's my app
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', function(req, res){
console.log(req.body);
res.render('index', {
infoVoos: 'acesso_inicial'
});
});
app.post('/pesquisar', function(req,res){
console.log("");
console.log("");
console.log(req.body);
res.send('ok');
});
app.listen(3000);
console.log('############');
console.log('Server on');
console.log('');
module.exports = app;
I changed the parameter of the input tag from "id" to "name" and it's working fine now.
original
<form action="/pesquisar" method="post">
<input type="text" id="cO">
<input type="text" id="cD">
<input type="submit">
</form>
new
<form action="/pesquisar" method="post">
<input type="text" name="cO">
<input type="text" name="cD">
<input type="submit">
</form>
thankx guys

How to redirect to another page after serving a post request in Node.js?

I want to save the data submitted by the user through a form using post method and then redirect it to another html page that I have on my local machine, is there any way to achieve this using Node.js or express how do I do that?
Here is the html code for form:
<html>
<head></head>
<body>
<form action="post_register.html" method="POST">
university name:<input type="text" name="name" placeholder="University name"><br>
faculty Username:<input type="text" name="facul" placeholder="faculty username"><br>
password:<input type="password" name="password" placeholder="password"><br>
<button >register</button>
</form>
</body>
and here is the javascript file:
var express = require("express");
var app = express();
var bodyparser=require("body-parser");
app.use(bodyparser.urlencoded({ extended: true }));
app.listen(3000);
app.get("/domain_register",function(req,res)
{
res.sendFile(__dirname+"/domain_register.html");
})
app.post("/post_register",function(req,res)
{
console.log(req.body);
res.end("yes");
});
all I want is that after pressing submit button the data is received and the user is redirected to post_register.html file.
I tested below code in my computer and it worked. I added res.redirect('/success') line to the post request handler and created an handler for /success path:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
You can change /success path with your naming choice.
App.js
var express = require('express')
var app = express()
var bodyparser = require('body-parser')
app.use(bodyparser.urlencoded({ extended: true }))
app.listen(3000)
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
app.get('/success', function (req, res) {
res.sendFile(__dirname + '/success.html')
})
app.post('/register', function (req, res) {
console.log(req.body)
res.redirect('/success')
})
index.html
<html>
<head></head>
<body>
<form method="post" action="/register">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
</body>
</html>
success.html
<html>
<head></head>
<body>
<h1>Welcome</h1>
</body>
</html>

Nodejs post method - req.body.variable undefined

I have the following App.js:
var express = require('express'),
app = express(),
engines = require('consolidate'),
MongoClient = require('mongodb').MongoClient,
assert = require('assert'),
bodyParser = require('body-parser')
app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended : true }));
// app.use(bodyParser.urlencoded());
// app.use(bodyParser.json());
app.post('/insert_movie', function (req, res) {
var movieName = req.body.movie_name;
console.log(movieName);
});
// No route matching:
app.use(function (req, res) {
res.sendStatus(404);
});
var server = app.listen(3000, function () {
var port = server.address().port;
console.log('Express server listening on port %s.', port);
});
My html page:
<h1> Add new movies</h1>
<form action="/insert_movie" method="POST">
<input type="text" id="movie_name">
<input type="text" id="movie_year">
<input type="text" id="movie_imdb">
<input type="submit" value="Submit" />
</form>
When I enter values into the text boxes and press submit, my post method is hit ('/insert_movie'). However movieName is undefined not only that but req.body is {}
Can someone explain to me what I'm doing wrong here as I've gone through many solutions on this website however they're all pointing the body parser being incorrectly setup, I've tried the following:
app.use(bodyParser.urlencoded({ extended : true }));
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
Neither of these fix my issue.
You need to add name attribute to the input elements. That's one of the things your body-parser library needs to parse the form.
<h1> Add new movies</h1>
<form action="/insert_movie" method="POST">
<input type="text" name="movie-name" id="movie_name">
<input type="text" name="movie-year" id="movie_year">
<input type="text" name="movie-url" id="movie_imdb">
<input type="submit" value="Submit" />
</form>
try to use this
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
limit: '500mb',
extended: true,
parameterLimit: 50000
}));
app.use(expressValidator());
app.use(bodyParser.json());
use multer middle ware for req.body
var app = require('express')();
var multer = require('multer);
var upload = multer().any();
//multer().any() upload both array and file
//add the multer middle ware in your router
app.post('/insert_movie',upload, function (req, res) {
var movieName = req.body.movie_name;
console.log(req.body);
console.log(movieName);
});
you can see the official npm blog
https://www.npmjs.com/package/multer

Cannot POST to app

A very simple page... server.js
var path = require("path");
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
app.listen(8000, function() {
console.log("listening on port 8000");
})
app.use(bodyParser.urlencoded());
app.use(express.static(path.join(__dirname, "./static")));
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index');
})
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/basic_mongoose');
var QuoteSchema = new mongoose.Schema({
name: String,
quote: String
})
var Quote = mongoose.model('Quote', QuoteSchema);
app.post('/quotes', function(req, res) {
console.log("POST DATA", req.body);
var quote = new Quote({name: req.body.name, quote: req.body.quote});
quote.save(function(err) {
if(err) {
console.log('something went wrong');
} else {
console.log('successfully added a quote!');
res.redirect('/main');
}
})
})
index.ejs
<html>
<head>
<title></title>
</head>
<body>
<div id='container'>
<h2>Welcome to Quoting Dojo</h2>
<form action='/quotes' method='post'>
<p>Your Name: <input type = 'text' id ='name'/><p>
<p>Your Quote: <input type='text' id ='quote'/><p>
<button id='add' type='submit'>Add Quote</button>
</form>
<button id='skip'>Skip to </button>
</div>
</body>
</html>
I get "cannot /POST" when I click the submit button. Anyone?
Server loads, html page in chrome shows up. I fill in the boxes and click "add". I get the route http://localhost:8000/quotes and the error Cannot POST /quotes. Not sure what I did as I have action='post' to /quotes and app.post in the server. I don't know if I have any other issues. Thanks.
Use the name attribute instead of id, name is sent to the server, id is not.
HTML input - name vs. id
<form action='/quotes' method='post'>
<p>Your Name: <input name='name' type = 'text' id ='name'/><p>
<p>Your Quote: <input name='quote' type='text' id ='quote'/><p>
<button id='add' type='submit'>Add Quote</button>
</form>

Categories

Resources