I am using boostrap (via MDB 4) and am trying to get the contact form to work. I have the form presenting as expected. It contains the following button outside the </form> tag
<a class="btn btn-primary" onclick="document.getElementById('contact-form').submit();">Send</a>
The opening line of the form is:
<form id="contact-form" name="contact-form" action="/contact" method="POST">
I am trying to understand how I get the form contents to nodejs and have the following in my Express routes
app.post('/contact', function(req, res){
console.log(req.body.name);
console.log(req.body.email);
console.log(req.body.subject);
console.log(req.body.message);
// code to store here later
});
I know this I am hitting this block as I can console out text from within the route but I get an error every time:
TypeError: Cannot read property 'name' of undefined
All the examples seem to use PHP but I would have thought nodejs would be more than enough for this? I don't have PHP on the box and would rather avoid it if I can stay in nodejs. Anyone got some pointers for me?
It might be worth noting that jquery is used but I don't know if that links in here? The following is at the foot of my html
<script type="text/javascript" src="js/jquery.min.js"></script>
Solved by adding the following to my index.js
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());
Now when I console.log(req.body); is get:
{
name: 'name',
email: 'name#x.y',
subject: 'test',
message: 'test'
}
I created solution for you:
//connect express
var express = require('express');
var path = require('path');
var ejs = require('ejs');
var partials = require('express-partials');
var app = express();
app.use(express.json());
app.use(partials());
app.use(express.urlencoded({ extended: false }));
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs');
//top level routing
app.get('/', (req, res) => {
res.render('index.ejs')
});
app.post('/contact', function(req, res){
res.render('thanks.ejs', {body: req.body})
});
//start server
var http = require('http');
var port = 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
<!--- start index.ejs -->
<form action="/contact" method="post" class="form-signin">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" placeholder="Enter name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" name="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="name">Subject</label>
<input type="text" class="form-control" name="subject" placeholder="Enter subject">
</div>
<div class="form-group">
<label for="name">Message</label>
<textarea type="text" class="form-control" name="message" placeholder="Enter message"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<!--- end index.ejs -->
<!--- start thanks.ejs--->
<%=JSON.stringify(body)%>
<!--end thanks.ejs --->
<!--- start layout.ejs --->
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="content">
<%-body -%>
</div>
</div>
</body>
</html>
<!--- end layout.ejs --->
My answer is based on this resource https://exceed-team.com/tech/form-submit-with-bootstrap-and-nodejs
Related
this is the error
listing form port 4000
Connection Sucessfull
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received an instance of TypeError
at new NodeError (node:internal/errors:371:5)
at validateString (node:internal/validators:119:11)
at extname (node:path:837:5)
at new View (D:\MERN\mernbackend\node_modules\express\lib\view.js:56:14)
at Function.render (D:\MERN\mernbackend\node_modules\express\lib\application.js:570:12)
at ServerResponse.render (D:\MERN\mernbackend\node_modules\express\lib\response.js:1012:7)
at D:\MERN\mernbackend\src\app.js:30:13
at Layer.handle [as handle_request] (D:\MERN\mernbackend\node_modules\express\lib\router\layer.js:95:5)
at next (D:\MERN\mernbackend\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\MERN\mernbackend\node_modules\express\lib\router\route.js:112:3) {
code: 'ERR_INVALID_ARG_TYPE'
}
this is the app.js file
const path = require('path');
const hbs = require('hbs');
const app = express();
require('./db/connect');
const port = process.env.PORT || 4000;
const templatePath = path.join(__dirname, '../templates/views')
const partialsPath = path.join(__dirname, '../templates/partials')
app.set('view engine', 'hbs');
app.set('views', templatePath)
hbs.registerPartials(partialsPath);
app.get('/', (req, res) => {
res.render('index')
})
app.get('/register', (req, res) => {
res.render('register')
})
app.get('/login', (req, res) => {
res.render('login')
})
app.post('/register', async (req, res) => {
try {
console.log(req.body.fname);
} catch (err) {
res.render(err)
}
})
app.listen(port, (err) => {
console.log(`listing form port ${port}`);
})```
**this is register.hbs file**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{>headLink}}
<title>Register</title>
</head>
<body>
<style>
/* Chrome, Safari, Edge, Opera */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Firefox */
input[type=number] {
-moz-appearance: textfield;
}
</style>
{{>nav}}
<form action="/register" method="POST">
<label> Firstname </label>
<input type="text" name="firstname" size="15"/> <br> <br>
<label> Middlename: </label>
<input type="text" name="middlename" size="15"/> <br> <br>
<label> Lastname: </label>
<input type="text" name="lastname" size="15"/> <br> <br>
<label>
Course :
</label>
<select>
<option value="Course">Course</option>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option>
<option value="B.Tech">B.Tech</option>
<option value="MBA">MBA</option>
<option value="MCA">MCA</option>
<option value="M.Tech">M.Tech</option>
</select>
<br>
<br>
<label>
Gender :
</label><br>
<input type="radio" name="gender"/> Male <br>
<input type="radio" name="gender"/> Female <br>
<input type="radio" name="gender"/> Other
<br>
<br>
<label>
Phone :
</label>
<input type="text" name="country code" value="+91" size="2"/>
<input type="number" name="phone" size="10"/> <br> <br>
Address
<br>
<textarea cols="80" rows="5" value="address" name="address">
</textarea>
<br> <br>
Email:
<input type="email" id="email" name="email"/> <br>
<br> <br>
Password:
<input type="Password" id="pass" name="pass"> <br>
<br> <br>
Re-type password:
<input type="Password" id="repass" name="repass"> <br> <br>
<input type="submit" value="register"/>
</form>
</body>
</html>
Try adding / in second argument in line number 7
const templatePath = path.join(__dirname, '/../templates/views')
similarly for line number 8
I am learning express node.js and trying to run simple calculator code but anytime i press on the button i don't get any response back and also i don't get any errors in my code so i am kind of lost of what i am doin wrong. here is the sample of it so hoping someone can pinpoint me where i am goin wrong will include html code and calculator.js. Thank you in advance.
index.html
<body>
<h1>Calculator</h1>
<form action="/" method="post">
<input type="text" name="num1" placeholder = "first number" value="">
<input type="text" name="num2" placeholder="second number" value="">
<button type="button" name="submit">Calculate</button>
</form>
</body>
calculator.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var result = num1 + num2;
//this line to show result in hyper
console.log(req.body);
res.send("The result is: " + result);
});
app.listen(3000, function(){
console.log("Server running on port 3000");
});
the problem lies in your button type. To submit a form using a button in html, you need to specify the type not as button, but as type.
<form action="/" method="post">
<input type="text" name="num1" placeholder = "first number" value="">
<input type="text" name="num2" placeholder="second number" value="">
<button type="submit" name="submit>Calculate</button>
</form>
This is my code app.js code
var express = require("express");
var app = express();
var bp = require("body-parser");
app.use(bp.urlencoded({extended: true}));
var friends = ["babba","lkshjk","kfhkd"];
app.get("/",function(req,res){
res.send("homepage");
});
app.get("/friends",function(req,res){
res.render("friends.ejs",{friends : friends});
});
app.post("/addfriends",function(req,res){
res.send("works fine");
});
var server = app.listen(2700 ,function() {
console.log("started");
});
and this is friends.ejs code
<h1>
friends list
</h1>
<% friends.forEach(function(friend){ %>
<li> <%= friend %> </li>
<% }); %>
<form action="/addfriend?" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
i just need "works fine " in my '/addfriend'
but i am getting
cannot get /addfriend in chrome
this works fine in postman when i try to debug
Your form have to point to the express route.
It should be:
<form action="/addfriends" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
Instead of
<form action="/addfriend?" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
You should declare your route equal you did in express route:
app.post("/addfriends",function(req,res){
res.send("works fine");
});
I have a simple html uploading form
<h1>Upload File Here</h1>
<form methods="post" enctype="multipart/form-data" action="/">
<input type="file" name="filename" /> <input type="submit" value="upload" />
</form>
I want uploaded files to hit a "/upload" folder. I am using the following express code to do this.
const express = require("express");
const app = express();
upload = require("express-fileupload");
app.listen(80);
app.use(upload());
console.log("Server Started");
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/", (req, res) => {
if (req.files) {
var file = req.files.filename,
filename = file.name;
file.mv("/upload/" + filename, err => {
if (err) {
console.log(err);
res.send("error occured");
} else {
res.send("done!");
}
});
}
});
When I start the server and go to localhost in Chrome, I see the upload form. If I try to upload something, the url box changes to reflect the file I tried to upload, but the file does not appear in the '/upload' folder. Any ideas on what obvious mistake I'm making??
Thanks!
The solution is in my form. I need to set the action="http://localhost:80/upload"
New HTML is
<h1>Upload File Here</h1>
<form
ref="uploadForm"
id="uploadForm"
action="http://localhost:80/upload"
method="post"
enctype="multipart/form-data"
>
<input type="file" name="filename" /> <input type="submit" value="upload" />
</form>
The solution is in my form. I need to set the
action="http://localhost:80/upload"
New HTML is
<h1>Upload File Here</h1>
<form
ref="uploadForm"
id="uploadForm"
action="http://localhost:80/upload"
method="post"
enctype="multipart/form-data"
>
<input type="file" name="filename" /> <input type="submit" value="upload" />
</form>
How do I submit a post request for multiple form fields using a button?
I'm trying to create a login page where the user clicks a single button to submit their email and password. I'm using Heroku with Node.js and Express.
I'm receiving the following error message when i try and run the app
login.ejs:
<link rel="stylesheet" type="text/css" href="/stylesheets/login.css" />
<div class="wrapper">
<form class="form-signin">
<h2 class="form-signin-heading">Login</h2>
<input type="text" class="form-control" name="email" placeholder="Email Address" required="" autofocus="" />
<input type="password" class="form-control" name="password" placeholder="Password" required=""/>
<label class="checkbox">
<input type="checkbox" value="remember-me" id="rememberMe" name="rememberMe"> Remember me
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit" value="Submit">Login</button>
</form>
index.js
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.post('form-signin', function(request, response){
console.log(request.query.email);
console.log(request.query.password);
}
app.get('/', function(request, response) {
response.render('pages/index')
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
I believe the problem has to do with the following line in index.js:
app.post('form-signin', function(request, response){
console.log(request.query.email);
console.log(request.query.password);
}
The answer is literally spelled out for you in the error message you received.
In index.js, go to line 17 and add a ); after the }
app.post('form-signin', function(request, response){
console.log(request.query.email);
console.log(request.query.password);
});
Well the error message says you are missing a closing brace. So to solve that add another ')' at the end of the piece of code :
app.post('form-signin', function(request, response){
console.log(request.query.email);
console.log(request.query.password);
}); // <---- Notice the missing brace