Im using express, node, bodyParser to pull information from a contact form and post it to the terminal. When I run the code and access my demo site through LocalHost:3000, upon submitting, my input items are not showing up in the terminal.
I've tried changing the form attributes action="send" action="/send" action="/"
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const nodemailer = require('nodemailer');
const app = express();
// View engine setup
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
// Static folder
app.use('/public', express.static(path.join(__dirname, 'public')));
/ Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.render('contact', { layout: false });
});
app.post('/send', (req, res) => {
console.log(res.body);
});
//Form HTML code
<form action="send" method="POST">
<input name="name" type="text" id="name" placeholder="NAME: First & Last">
<input name="email" type="text" id="email" placeholder="EMAIL:">
<textarea name="text" id="text" cols="30" rows="10" placeholder="QUESTION OR INQUIRY:"></textarea>
<br>
<button type="submit">Submit</button>
</form>
Have you tried console logging the req instead of the res for the app.post?
If you are doing console.log(req.body) then this should output a long json object. If this is not happening, then you are not hitting the url.
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const nodemailer = require('nodemailer');
const app = express();
// View engine setup
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
// Static folder
app.use('/public', express.static(path.join(__dirname, 'public')));
// Body Parser Middleware
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.render('contact', { layout: false });
});
app.post('/send', (req, res) => {
console.log(res.body);
});
The problem is in your html code. I have made some changes, Try this.
//Form HTML code
<form action="http://localhost:9000/send" method="POST">
<input name="name" type="text" id="name" placeholder="NAME: First & Last">
<input name="email" type="text" id="email" placeholder="EMAIL:">
<textarea name="text" id="text" cols="30" rows="10" placeholder="QUESTION OR INQUIRY:"></textarea>
<br>
<button type="submit">Submit</button>
</form>
Related
In my Node app i have a simple form like this:
<form action="/createProject" enctype="multipart/form-data" method="post">
<div class="project-field">
<p class="subtitleFont project-field-name">NOME</p>
<input type="text" name="name" required>
</div>
<div class="project-field">
<p class="subtitleFont project-field-name">IMMAGINI</p>
<input type="file" multiple name="images" required>
</div>
<div class="project-field">
<button type="submit">Crea progetto</button>
</div>
</form>
This is the app.js configuration:
require('dotenv').config();
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const routes = require('./server/routes/index.js');
const app = express();
const port = process.env.PORT;
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
app.use(expressLayouts);
app.use(routes);
app.set('layout', './layouts/main');
app.set('view engine', 'ejs');
app.listen(port, () => {console.log('Listening to port '+port+'!')});
The multer configuration is this:
const multer = require('multer');
const storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, 'public/uploads/');
},
filename: function(req, file, cb){
cb(null, new Date().toISOString() + file.originalname);
}
})
const upload = multer({storage: storage});
When i trigger the action and console.log serverside req.body and req.files they seem to be empty.
Is there any way to solve this problem?
So I want to use a form in my svelte page to send emails with nodemailer. I want to integrate my svelte form with my contact.js file. I have a template contact.js file, but it uses express-handlebars to integrate with a contact.handlebars form. So instead of using handlebars, I am using svelte here. How can I integrate them??
the contact.js template:
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const mailer = require('nodemailer');
const app = express();
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/contact', (req, res) => {
res.render('contact');
});
the svelte form inside contact.svelte:
<CourseWrapper {user}>
<main>
<h2>Contact Us</h2>
<p>Send us a message about your questions or suggestions of any kind.</p>
<ShadowedCard>
<form on:submit|preventDefault={submit}>
<InputGeneric label="Name" bind:value={name} placeholder="Enter your name" />
<InputGeneric
label="Email"
type="email"
bind:value={email}
placeholder="Enter your email" />
<InputGeneric label="Subject" bind:value={subject} placeholder="Enter your email subject" />
<InputGeneric label="Feedback" type={null}>
<textarea bind:value={message} placeholder="Enter your message" />
</InputGeneric>
{#if state === 'loading'}
<Loader.ThreeWavyBalls />
{:else}
<Button type="submit" color>Send</Button>
{/if}
</form>
</ShadowedCard>
</main>
</CourseWrapper>
I'm a newbie in node.js and svelte :( thank you in advance!
Instead of express-handlebars you'd need to use svelte-view-engine. You should then be able to use it as an express view engine:
const bodyParser = require('body-parser');
const svelteViewEngine = require("svelte-view-engine");
const mailer = require('nodemailer');
const app = express();
let engine = svelteViewEngine({
env: "dev",
template: "./template.html",
dir: "./pages",
type: "html",
buildDir: "../artifacts/pages",
});
app.engine(engine.type, engine.render);
app.set("view engine", engine.type);
app.set("views", engine.dir);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/contact', (req, res) => {
// pass user object to template
res.render('contact', { user: //tbd });
});
See https://github.com/svelte-view-engine/sve-app for an example app.
I have two ejs in my views folder
I have created very simple ejs to see if I can send the variable from one ejs to another ejs.
a.ejs in veiws file
<form name="input" action="\home" method="post">
<input type='checkbox' checked>Cheese
<input type="submit" value="Submit" href="validation.ejs">
</form>
b.ejs has
<h1><% post my variable here%></h1>
in my node js this is what i did
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index', { title: 'EJS Demo' });
});
app.post('/', (req, res) => {
const a = req.body.a;
res.get('index2',a);
});
app.listen(3000, () => {
console.log('Listening....');
});
i think the post has to do something in here...
I think you need to submit a value from form1 in page1 and pass that variable to page2
if thats the case you can do like this
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'ejs');
// send the page1 to the user
app.get('/', (req, res) => {
res.render('page1', { title: 'EJS Demo' });
});
//capture the submit from the user and then send another page
//to the user
app.post('/submitForm', (req, res) => {
const a = req.body.valueFromA;
res.render('page2',a);
});
app.listen(3000, () => {
console.log('Listening....');
});
<form name="input" action="\home" method="post">
<input type='checkbox' checked>Cheese
<input type="submit" value="Submit" href="validation.ejs">
</form>
<!-- page1 form1 -->
<html>
<head>
<title> <& title &> </title>
</head>
<form action='/submitForm' method='post'>
<input type='text' value='' name='valueFromA' />
<input type='submit' />
</form>
</html>
<!-- page2 ejs -->
<html>
<body>
<p> <% value %> </p>
</body>
</html>
b.ejs has
<h1><% post my variable here%></h1>
in my node js this is what i did const
I have an express app that takes basic user input data. All of my get routes work fine but when submit a post request to the server I get a 404 on the url I'm posting to even though I have this page in my views folder.
app.js:
var express = require('express');
var path = require('path');
var consolidate = require('consolidate');
var bodyParser = require('body-parser');
var database = require('./database/database');
var Patient = require('./models/models').Patient;
var morgan = require('morgan');
var routes = require('./routes');
var app = express();
app.engine('html', consolidate.nunjucks);
app.set('view engine', 'html');
app.set('views', './views');
app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(3055);
module.exports = app;
routes/index.js:
const express = require('express');
var bodyParser = require('body-parser');
var Patient = require('../models/models').Patient;
const router = express.Router();
router.get('/', function(req, res, next){
res.render('index.html');
});
router.post('/addsubject', function(req, res, next){
Patient.create(req.body).then(function(patient){
res.redirect('/profile');
}).catch(function(err){
if(error.name === "SequelizeValidationError"){
} else {
return next(err);
}
}).catch(function(error){
res.send(500, error);
});
});
router.get('/profile', function(req, res, next){
res.render('./profile.html');
});
router.get('/addsubject', function(req, res, next){
// .... do something here ..
});
module.exports = router;
I have the <form action="/addsubject" method="post"> in my index.html file.
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>dabl Demographic</title>
<body>
<h2>Add Subject</h2>
<form action="/addsubject" method="post">
<label for="fname">First Name: </label>
<input type="text" name="fname" id="fname">
<br>
<label for="sname">Second Name: </label>
<input type="text" name="sname" id="sname">
<br>
<label for="dob">dob: </label>
<input type="text" name="dob" id="dob">
<br>
<label for="laterality">Laterality: </label>
<input type="text" name="laterality" id="laterality">
<br>
<button>Submit</button>
</form>
</body>
</html>
You pass wrong function (error handling function) to the POST route.
Just remove first "err" param from the function like this:
router.post('/addsubject', function(req, res, next){
Use body-parser middleware before app.router
...
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
...
Problem solved:
}).catch(function(err){
if(error.name === "SequelizeValidationError"){
next(err); //next(err); called inide this block no more 404 error
}
User input is now succesfully passed through the body-parser.
This is my server.js file:
var express = require("express");
var bodyParser = require("body-parser");
var controllers = require('./controllers');
var app = express();
controllers.init(app);
app.set('view engine', 'vash');
app.use(bodyParser());
app.use(express.static(__dirname + "/public"));
app.listen(5000);
This is my index.js code in controllers folder:
(function(controllers){
var homeController = require('./homeController');
controllers.init = function(app){
homeController.init(app);
};
})(module.exports);
This is my homeController.js code:
(function(homeController){
homeController.init = function(app){
app.get('/', function(req, res){
res.render('index', {title: "The Board"});
});
app.post("/", function(req, res){
console.log(req.headers);
console.log(req.body);
});
};
})(module.exports);
And this is my HTML:
#html.extend('layout', function(model){
#html.block('body', function(model){
#if(model.error){
<p class="text-error">Error occurred: #model.error</p>
}
<div class="row">
<form action="/" method="post">Enter your name:
<input type="text" name="userName" placeholder="..." />
<br>
<button type="submit">Submit</button>
</form>
</div>
})
})
When I make the post action req.body is undefined. How can I solve this problem?
Move app.use(bodyParser()); before route declaration controllers.init(app);