I'm trying to use post with express and bodyparser to insert data into MYSQL from a form in a ejs file. It keeps returning null, so it seems that my data is not parsed from the form to my backend.
Could you please help?
Here is my server.js
app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ limit: '100mb', extended: false }));
dotenv.config();
// Set the default views directory to html folder
app.set('views', path.join(__dirname, 'html'));
// Set the folder for css & java scripts
app.use(express.static(path.join(__dirname,'css')));
app.use(express.static(path.join(__dirname, 'node_modules')));
// Set the view engine to ejs
app.set('view engine', 'ejs');
app.use('/', routes);
app.listen(3000, () => {
console.log(`Server is running at ${process.env.SERVER_PORT}`);
});
my index.js
router.post('/save', (req, res) => {
const formData = { username : req.body.username, account : req.body.account, email : req.body.email,
address : req.body.address, start_date : req.body.start_date, picture : req.body.picture,
request : req.body.request };
const sqlPut = "INSERT INTO dbTable ?";
const query = dbconn.conn.query(sqlPut, formData, (err, results) => {
if(err) throw err;
res.redirect('/about')
})
})
Here is my ejs file with the form.
<div class="container" >
<form id="contact" action="/save" method="post">
<h3>New scholar form</h3>
<fieldset>
<input placeholder="username" id="username" type="text" tabindex="1" required autofocus>
</fieldset>
<fieldset>
<input placeholder="account" id="account" type="text" tabindex="2" required>
</fieldset>
<fieldset>
<input placeholder="email" id="email" type="email" tabindex="3" required>
</fieldset>
<fieldset>
<input placeholder="bnc_address" id="bnc_address" type="text" tabindex="4" required>
</fieldset>
<fieldset>
Scholar start date <input placeholder="start_date" type="date" tabindex="4" required>
</fieldset>
<fieldset>
<input placeholder="picture" id="picture" type="text" tabindex="4" required>
</fieldset>
<fieldset>
<textarea placeholder="Scholar request..." id="request" tabindex="5" required></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>
I can retrieve data from the database and post it just fine. I just haven't figured this one out.
I haven't posted here in a while, so bear with me
You need to change this line:
app.use(express.urlencoded({ limit: '100mb', extended: true }));
Parses the text as URL encoded data(which is how browsers tend to send form data from regular forms set to POST) and exposes the resulting object (containing the keys and values) on req.body.
I imported body-parser without using it. After I removed the import it started working.
Removed this, even though it was not used, it started working after:
const bodyParser = require("body-parser");
Related
I am trying to get data from user and then adding it to my database. But whenever i send a post request through form and try to print data in the request body it says "undefined".
I tried finding answer online but it didn't help. The error could be silly but an anyone tell me what it could be?
<form action="/products" method="POST">
<legend for="name">Name</legend>
<input type="text" name="name" id="name" placeholder="Enter Product Name" required><br><br>
<legend for="price">Price</legend>
<input type="text" name="price" id="price" placeholder="Enter Product Price" required><br><br>
<legend for="img">Image</legend>
<input type="text" name="img" id="img" placeholder="Enter Product Image URL"><br><br>
<legend for="img">Description</legend>
<textarea name="desc" id="desc" placeholder="Enter Product Description" rows="5" cols="50"></textarea><br><br>
<button type="submit">Submit</button>
</form>`enter code here`
This is the main app file
const express=require("express");
const app=express();
const mongoose=require("mongoose");
const path=require("path");
const routes=require("./routes/ec-routes");
const seed=require("./seed");
app.use(express.json())
app.set("view engine","ejs");
app.set("views",path.join(__dirname,"views"));
mongoose.connect("mongodb://localhost:27017/e-commerce")
.then(()=>console.log("DB Connected"))
.catch((err)=>console.log(err));
app.use(express.static(path.join(__dirname,"public")));
app.use(routes);
app.use(express.urlencoded({extended:false}));
//seed();
app.get("/",(req,res)=>{
res.send("Home page");
});
app.listen(3000,(req,res)=>{
console.log("Up At 3000")
})
This is routes file
const express=require("express");
const router=express.Router();
const Product=require("../models/product");
router.get("/products",async (req,res)=>{
const products=await Product.find({});
res.render("products/home",{products});
})
router.get("/products/new",(req,res)=>{
res.render("products/new");
})
router.post("/products",async (req,res)=>{
const product={
...req.body
}
console.log(req.body)
res.redirect("/products");
})
module.exports=router;
you need to use express.urlencoded({extended:false}) middleware
before you hit the router,
so that the body which is sent by html post method will be attached under req.body object
in your case
app.use(routes);
app.use(express.urlencoded({extended:false}));
it should be like this
app.use(express.urlencoded({extended:false}));
app.use(routes);
<form action="/signupOk" method="post" class ="signupForm">
<input type="text" name="id" placeholder="." class ="name" required><br>
<input type="password" name="password" placeholder="" required><br>
<input type="text" name="nickname" placeholder="" required><br>
<input type="email" name="nickname" placeholder="" required><br>
<input type="tel" name="nickname" placeholder="" required><br>
<input type="address" name="nickname" placeholder="" required><br>
<input type ="text" name="code" placeholder=""><br>
<input type ="submit" value ="hi"/>
</form>
This is front-side code
var express = require('express');
var nodeCmd = require('node-cmd');
var fs = require("fs");
var path = require('path');
var favicon = require('serve-favicon');
var app = express();
var server = require('http').createServer(app);
var bodyParser = require('body-parser');
var request = require('request');
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public')); //
app.use(favicon(__dirname + '/0101c_icon.ico'));
var port = 1010;
var AppStart = function() { console.log(''); }
server.listen(port, AppStart);
And I'll skip some codes about sever starting.
// signup
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(path.join(__dirname,'public')));
app.post('/signupOk', function(req, res){
var id = req.param("id");
console.log(id);
});
And this is the codes to send datas from form tags to database.
But I wanna know were datas moved ok right here correctly. I cannot use alert, and about using console.log, After submit, Broswer is refreshed so console log is clean. How can I check datas arrived there correctly? Thanks.
Four input fields in your form have the same name. That probably isn’t helping things.
‘body-parser‘ puts your form field values into ‘req.body‘ . ‘req.params‘ is for route parameters (slugs in the url path.).
So, try ‘console.log(req.body);‘ to see the parameters.
I am using nodejs with express and ejs.
Every one on internet ask how to pass value from node to the view, but what about the opposite?
For example, I ask my user to input a string in a form, when the user clicks the button, how can I get this string without passing it as a parameter in the url?
The form:
<div class="container">
<form style="width:50%">
<div class="form-group">
<label for="text">Name of the product</label>
<input type="text" class="form-control" id="pName">
</div>
<div class="form-group">
<label for="text">Reciever</label>
<input type="text" class="form-control" id="reciever">
</div>
<div class="form-group">
<label for="text">Location</label>
<input type="text" class="form-control" id="location">
</div>
<!-- <div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>-->
<button type="submit" class="btn btn-default">Submit</button>
</form>
The app.js
var express = require('express');
var app = express();
//ALL GLOBAL VARIABLES
var port = 8080;
app.get('/', function(req, res) {
res.render('index.ejs');
});
app.get('/barcode', function(req,res) {
res.render('barcode.ejs');
});
app.listen(port);
I know I can do this:
app.get('/url/:parameter', function(req.res) {
var foo = req.params.parameter;
}
But if I don't want to use the URL, is it possible to retrieve the data?
Use POST as a method for your html form
<form action="/myapi" method="post">
<input type="text" class="form-control" id="pName" name="pName">
<button type="submit" class="btn btn-default">Submit</button>
</form>
And then handle the client form "action" with app.post on the back end
app.post('/myapi', function(req, res) {
res.send('The pName is "' + req.body.pName + '".');
});
You can use POST method instead of GET. You need to change the route in your Express to
app.post('/url', function(req.res))
and add a method on your form
<form style="width:50%" method="POST">
If you use a POST request the parameters are not part of the URL. E.g.
app.post('/path', function(req, res) {
...
//You can retrieve the parameters of the POST request here
]);
You'll need the body-parser module to be able to get the POST parameters. Here's an answer about how to get the POST parameters once you've set up the route.
Your form should have a method and and action:
<form action="/path" method="POST">...</form>
From your question, In general if you want to get a value from the unique id, you will store that value as a global variable. so you can easily get the current user and user related details.
I am trying to show my form data to another html page. This is my server.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var path=require('path');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '/')));
app.post('/myaction.html', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
And this is my 'index.html'
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo Form</title>
</head>
<body>
<div id="contact">
<h1>Enter the values</h1>
<form action="/myaction.html" method="post">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" />
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Enter your email address" />
<label for="message">Message:</label>
<textarea id="message" placeholder="What's on your mind?"></textarea>
<input type="submit" value="Send message" />
</fieldset>
</form>
</div>
</body>
</html>
Now, it is working properly and the name is reflecting in the myaction.html page. But I want to stylize the 'myaction.html' page a bit and make it look more presentable. Is there any way to add more html tags and text to the page or to display the form data in an already existing page?
Use a template engine. A good one is EJS. First you have to use npm install ejs and then app.set('view engine', 'ejs'); inside your server.js . After that you will be able to create a new folder in your project named views and inside you can create index.ejs and other views files. Inside your server.js you can use res.render('index.ejs', {data: aJavascriptVariable, data1: moreVars}); . Finally to use this variables inside the .ejs files you can use <%= data %> or <%= data1 %>. Of course html can be written inside a .ejs file.
Hi i'm new to stack and programming, so i have a node project that when i run the server it calls the mandrill api and sends my email template to a hardcoded email, all i want to know is how do i get the email value from a form input field send it to server .js or wherever and send my template to that email
<div class="input-group emailInput emailInput2">
<form method="post" action="/send-email/invoiceEmail">
<input type="email" class="form-control input1 target" id="emailAddress" name="email" placeholder="Email Address">
<span class="input-group-btn">
<button id="emailAddress2" class="btn btn-secondary input2 emailbtn2 other" type="button" onclick ="validate()">
<div class="emailbtn">></div>
</button>
</span>
</form>
</div>
app.post("/send-email/invoiceEmail", function (req, res) {
var x = document.getElementById("emailAddress");
console.log(req.body.email);
var email = "mail#mail.com";
emailService.sendInvoiceEmail(email,function(data){
res.send("success");
},
function(error){
console.log(error);
})
});
Use bodyparser middleware to read form values. Include this to your main file.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Use req.body.email to read the email from the form.