I have form post job.html and a button post. I want that when someone submits this form the values save in database and then i get these values on another helper's feed.html page. Right now, my values are saving in database but i am unable to understand how to get those values in next page.
This is the part of html code for helpers feed.
<div class="col-md-10" >
<div> Description:
<input type="text" id="desc" name="budget"class="form-control">
<div>
<div> Category:
<input type="text" id="category" name="budget" class="form-control">
</div>
<div > City:
<input type="text" id="city" name="budget" class="form-control">
</div>
<div > Budget
<input type="text" id="budget" name="budget" class="form-control">
</div>
This is node.js file. post.js
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'sahoolat1',
database : 'fyp_sahoolat'
});
connection.connect(function(err){
if(err) throw err;
console.log("connected");
});
var app = express();
app.use(bodyParser.urlencoded({extended : false}));
app.use(bodyParser.json());
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/job post.html'));
});
app.post('/post',(request,response,next)=>{
var description=request.body.description;
var contact_number=request.body.contact_number;
var city=request.body.city;
var budget=request.body.budget;
var category=request.body.optradio;
var query=connection.query("insert into jobs(Jobs_id,Description,Category,City,Contact_number,Budget) values(?,?,?,?,?,?)",[null,description,category,city,contact_number,budget],function(err){
if(err)
console.log(err);
else
console.log("moving");
});
next();
});
app.get('/post',(request, response) => {
connection.query("SELECT * FROM jobs",(err, result) => {
if(err) {
console.log(err);
}
else {
console.log(result);
res.send(result);
}
});
});
app.listen(3000);
The code runs fine till the line where i am saving in database and it prints "moving" on console.
I want to get each field value in the respective text fiels(as shown in screenshot)
Related
My project was working fine till last week and now all of a sudden my post requests are not working . i tried all methods and read other questions of stack overflow but was unable to fix the issue . can some one please help me?
Issue : req.body is undefined and also whenever i try upload a file "cannot read property path of undefined" is the error.
i'm using express middle ware to parse the request body . i also have my form enctype to multipart/form-data..
Code snippet is below :
require('dotenv').config()
const express = require('express');
const app = express();
const router = express.Router();
const session = require('express-session');
const fs = require(`fs`);
const mysql = require(`mysql-await`);
const path = require('path');
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
const multer = require('multer');
const {storage} = require('../cloudinary');
const upload = multer({storage});
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "Sujanya#1978",
database: "dept"
});
con.connect((err) => {
if (!err) {
console.log("Connected");
}
else {
console.log(err)
}
})
router.get('/naaccircular',(req,res)=>{
(async () => {
let results = await con.awaitQuery('select* from dept.naaccircular;');
res.render('Naac_circular',{Egs : results})
})();
})
router.get('/naaccriteria',(req,res)=>{
(async () => {
flet results = await con.awaitQuery('select* from dept.naaccriteria;');
res.render('Naac_criteria_files',{Fgs : results})
})();
})
router.post('/naacaddcircular',upload.single('circularfile'),(req,res) => {
console.log(req.body);
const n = req.body.circularname;
const d = req.body.circulardate;
const l = req.file.path;
con.connect(function(err){
var records = [n,d,l];
con.query("insert into dept.naaccircular (cirname,cirlink,cirdate)
VALUES (?,?,?)", [n,l,d] , function (err, result, fields){
if (err) throw err;
})
});
console.log(n);
console.log(l);
console.log(d);
res.redirect('/naaccircular');
})
module.exports = router;
style="margin-top:80px; background-color: white;">
<form action="/naacaddcircular" method="POST" class="row g-3 form-container" enctype="multipart/form-data">
<h3 style="text-align: center;">Naac Circular</h3>
<div class="mb-3">
<label for="ii" class="form-label">Name</label>
<input id="ii" name="circularname" class="form-control" type="text" placeholder="Default input"
aria-label="default input example">
</div>
<div class="mb-3">
<label for="jj" class="form-label">Date</label>
<input id="jj" name="circulardate" class="form-control" type="date">
</div>
<div class="input-group mb-2">
<input type="file" class="form-control" name="circularfile"id="inputGroupFile04" aria-describedby="inputGroupFileAddon04"
aria-label="Upload">
<!--<button class="btn btn-outline-secondary" type="button" id="inputGroupFileAddon04">Button</button>-->
</div>
<button type="submit"
class="btn btn-primary position-relative start-50 botttom-0 translate-middle-x">Upload</button>
</form>
</div> ```
The problem is with cloudinary module. I have rectified it, there are no errors in the post method.
Once upload.single() function is removed from the router.post() function I'm able to get the req.body(),
full error is
This is my index.js
ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''sada'' at line 1
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
let cryptr = require('cryptr');
cryptr = new cryptr('myTotalySecretKey');
const jwt = require('jsonwebtoken');
var dir = path.join(__dirname, 'public');
app.use(express.static(dir));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(__dirname + 'public'));
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'trello',
password: 'trello',
database: 'trello'
});
connection.connect(function (err) {
if (!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
module.exports = connection;
app.post('/signup', (req, res) => {
let encryptedString = cryptr.encrypt(req.body.password);
let sql = 'insert into users(name, email, password) values ?';
let values = [req.body.name, req.body.email, encryptedString];
connection.query(sql, values, function (err, result) {
if (err) throw err;
return res.redirect('/login.html');
});
});
app.listen(3000);
my html form
<form action="/signup" method="POST">
<div class="username">
<input type="text" placeholder="User Name" name="name"></input>
</div>
<div class="username">
<input type="email" placeholder="Email" name="email" id="email"></input>
</div>
<div class="username">
<input type="password" placeholder="Password" name="password" id="password"></input>
</div>
<div class="button-signup-login">
<button class="add-card-btn btn">Sign Up</button>
<a class="signup-navigator" href="login.html">already a
user?</a>
</div>
</form>
i am pretty new to nodejs so can anybody tell me why there is this error coming
You have to add a placeholder for every value you insert:
let sql = 'insert into users(name, email, password) values (?, ?, ?)';
let values = [req.body.name, req.body.email, encryptedString];
This question already has answers here:
MongoDB - Error: document must have an _id before saving
(9 answers)
Closed 4 years ago.
I have a registration page that takes input username and password to store into a mongoDB.
When I click on the Register button, it loads an error page.
Which also causes a Mongoose Error in the terminal that says MongooseError: document must have an _id before saving at new MongooseError
Below are the code.
//server.js file
var express = require('express');
var app = express();
var port = 8888;
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
/*Body parser*/
app.use(bodyParser.urlencoded({
extended: true
}));
/*Database connection - MongoDB*/
//Created from the command earlier. Ensure this is done on the first_db instance
var username = 'admin';
var password = '123456';
var dbHost = 'localhost';
var dbPort = '27017';
var database = 'first_db';
var url = 'mongodb://' + username + ':' + password + '#' + dbHost + ':' + dbPort + '/' + database;
console.log('mongodb connection = ' + url);
mongoose.connect(url, function(err) {
if(err) {
console.log('connection error: ', err);
} else {
console.log('connection successful');
}
});
/***********
Declare all models here
***********/
//User model
var UserSchema = new mongoose.Schema({
_id: mongoose.Schema.ObjectId,
username: String,
password: String
});
var User = mongoose.model('user', UserSchema);
/***********
All routes go below
***********/
app.get('/', function (req, res, next){
res.sendFile( __dirname + '/index.html');
});
app.get('/register', function (req, res, next) {
res.sendFile( __dirname + '/register.html');
});
app.post('/register', function (req, res, next) {
User.create(req.body, function(err, saved) {
if(err) {
console.log(err);
res.json({ message : err });
} else {
res.json({ message : "User successfully registered!"});
}
});
});
app.listen(port, '0.0.0.0', function(){
console.log('Server running at port ' + port);
});
//register.html file
<html>
<head>
<title>My first NodeJS Website</title>
</head>
<body>
<p>Registration page</p>
<form action="/register" method="post">
<p>Username <input type="text" name="username" /></p>
<p>Password <input type="password" name="password" /></p>
<input type="submit" value="Register"/>
</form>
<p>Click here to go back. </p>
</body>
</html>
//index.html file
<html>
<head>
<title>My first NodeJS Website</title>
</head>
<body>
<p>Hello World!</p>
<form action="/login" method="post">
<p>Username <input type="text" name="username" /></p>
<p>Password <input type="password" name="password" /></p>
<input type="submit" value="Login"/>
</form>
<p>Not yet registered? Click here to create an account. </p>
</body>
</html>
You don't have to define the _id as mongoose.Schema.ObjectId in the User schema. MongoDB will implicitly generate the ID even if you don't define it in the schema and insert your object even if you don't provide value for _id. However, if you define it explicitly in the schema, Mongoose runs a validation check and expects you to provide the value - it will throw an error and your query won't even reach the database.
I am having an issue with trying to save data parsed from the browser to my mongodb database it would be great if someone could explain to me why I am getting the error I am and how to fix it, thanks.
App.js:
var print = require('./print');
var port = 1338;
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:1337/testdb';
MongoClient.connect(url, function(err, db) {
var collection = db.collection('users');
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
}
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render("post");
print("All is in order");
})
var collection = db.collection('users');
var name = app.post('/post', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
var name = req.body.name
var user1 = { "username": name };
collection.insert(user1, function(err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted %d documents into the "users" collection. The documents inserted with "_id" are:', result.length, result);
}
})
});
app.listen(port, function() {
print(`listening on ${port}`);
})
db.close();
})
Post.ejs:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSS3 Contact Form</title>
</head>
<body>
<div id="contact">
<h1>Send an email</h1>
<form action="http://127.0.0.1:1338/post" 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>
Error:
{ MongoError: server instance pool was destroyed
at Function.MongoError.create (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb-core\lib\error.js:29:11)
at basicWriteValidations (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb-core\lib\topologies\server.js:446:51)
at Server.insert (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb-core\lib\topologies\server.js:532:16)
at Server.insert (C:\Users\Programming\Documents\Web_Repo\\node_modules\mongodb\lib\server.js:383:17)
at executeCommands (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\bulk\ordered.js:455:23)
at OrderedBulkOperation.execute (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\bulk\ordered.js:508:10)
at bulkWrite (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\collection.js:652:8)
at Collection.insertMany (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\collection.js:522:44)
at Collection.insert (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\collection.js:824:15)
at C:\Users\Programming\Documents\Web_Repo\app.js:36:18
name: 'MongoError',
message: 'server instance pool was destroyed' }
Looks like Mukesh already told you the solution but like he mentioned your code structure can be improved.
So here's how I would do it,
Config file ~config.js
module.exports = {
localUrl: 'mongodb://localhost/testDb',
port: 1338
};
main file
var print = require('./print');
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var config = require('./config.js');
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render("post");
print("All is in order");
})
app.listen(config.port, function() {
print(`listening on ${config.port}`);
})
MongoClient.connect(config.localUrl, function(err, db) {
if(err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
return;
}
var collection = db.collection('users');
app.post('/post', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
collection.insert({
username : req.body.name
}, function(err, result) {
if (err) {
console.log(err);
db.close();
return;
}
db.close();
})
});
})
In 'app.js' I have
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
'index.js' full codes
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
router.get('/', function(req, res, next) {
res.render('index', { title: 'Here' });
});
router.post('/manager', function(req, res, next) {
var connection = mysql.createConnection({
host : 'localhost',
user : req.body.username,
password : req.body.password,
database : 'shops'
});
connection.connect(function(err){
if(!err)
res.render('manager', { title: 'Here' });
else
console.log("Error connecting database ...");
});
});
module.exports = router;
In 'index.html' login form
<form id='login' method='post' action='manager'>
Username<br>
<input id='username' type='text'><br>
Password<br>
<input id='password' type='password'><br>
<input type='submit' value='Login'>
<input type='reset' value='Reset'>
</form>
In index.js line 12-13
req.body.username
req.body.password
Everytime I try to parse data from html form, they return 'undefined'. I'm new to node.js scripting. Am I doing something wrong?
You're missing name attributes on your <input> tags. Add them like:
<form id='login' method='post' action='manager'>
Username<br>
<input id='username' name='username' type='text'><br>
Password<br>
<input id='password' name='password' type='password'><br>
<input type='submit' value='Login'>
<input type='reset' value='Reset'>
</form>