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);
Related
Having an issue with processing post request in node.js and it is showing the error: Cannot POST /index.html
Since body-parser is deprecated, I am stuck with this error
const express = require("express");
const app = express();
app.use(express.json({ limit: '50mb' }));
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;
res.send(String(result));
});
app.listen(3000, function(){
console.log("Server is running on port 3000");
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Calculator</h1>
<form action="index.html" method="post">
<input type="text" name="num1" placeholder="First Number">
<input type="text" name="num2" placeholder="Second Number">
<button type="submit" name="submit">Calculate</button>
</form>
</body>
</html>
I don't get it. What is your requirement with these code snippets?
Since body-parser is deprecated, I am stuck with this error
body-parser is now part of Express and you can just get it by writing,
app.use(express.urlencoded({ extended: false }));
error: Cannot POST /index.html
The reason Express throw this error is because, you don't have matching POST route. Instead you have POST / route. I would suggest you to update the <form>'s action to / instead of index.html.
<form action="/" method="post">
<input type="text" name="num1" placeholder="First Number" />
<input type="text" name="num2" placeholder="Second Number" />
<button type="submit" name="submit">Calculate</button>
</form>
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");
<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.
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.
I'm a little be confused when it comes to calling APIs over node.js.
I have a server running node js where I can install frameworks like the one for chargebee.
I created a html page where I make subscriptions etc. Now I would want to call the corresponding chargebee function to make the subscription.
If I try to load chargebee with require('chargebee')it failes. I can only load it in the server js.
So how would it be possible for me to use the functionalities of chargebee?
Is it possible that I invoke a function from chargbee by a click on the button? Do i have to provide this function by express?
I think I did not understand the difference between client side code and server side code when it comes to node.js.
How can function on the server side be invoked by clicks on html buttons for example?
In order to trigger request from client side you can use forms or AJAX. Here is an example with express framework in which form is used to trigger request and create subscription in chargebee
Client-Side Code:
<html>
<body>
<form action="/subscribe" method="post">
<label for="name">First Name:</label>
<input type="text" id="name" name="customer[first_name]" placeholder="first name" />
<br />
<label for="name">Last Name:</label>
<input type="text" id="name" name="customer[last_name]" placeholder="last name" />
<br />
<label for="email">Email:</label>
<input type="email" id="email" name="customer[email]" placeholder="Enter your email address" />
<br />
<input type="submit" value="Create Profile" />
</form>
</body>
</html>
Node-Server code:
var express = require('express');
var chargebee = require("chargebee");
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
chargebee.configure({site : "<<site_name>>",
api_key : "<<api_key>>"
app.get('/', function(req, res){
res.sendFile(__dirname + '/form.html');
});
app.post('/subscribe', function(req, res){
var params = req.body;// getting form params as JSON
params['plan_id']='enterprise'; // plan id that is present in your Chargebee site
chargebee.subscription.create(params).request(function(error,result){
if(error){
//handle error
console.log(error);
}else{
console.log(result);
var subscription = result.subscription;
res.writeHead(200, {
'content-type': 'text/plain'
});
res.write('Successfully created subscription\n\n' + 'id :: '+ subscription.id);
res.end();
}
});
});
app.listen(3000);
console.log("server listening on 3000");
It is possible with chargebee v3 . Hope This will solve your query
<!DOCTYPE html>
<html>
<head>
<title>chargebee Example</title>
<script src = "https://js.chargebee.com/v2/chargebee.js" data-cb-site = "your site name" > </script>
</head>
<body>
<!-- for creating subscription -->
<a href="javascript:void(0)" data-cb-type="checkout" data-cb-plan-id="30" >subscribe</a>
<!-- for managing portal -->
<a href="javascript:void(0)" data-cb-type="portal" >Manage account</a>
</body>
</html>