Context: Want to insert data in mongoDB database from node.js
Problem Statement: I am trying to insert data in the mongoDB database but thrown an error. Cant find it.
Present Output: Reference error
Attach Code:
filter.js
var server = require('http'),
express = require('express'),
http = require('http'),
fs = require('fs');
filter = express(),
io = require('socket.io'),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/filter_CheckBoxSchema', function(err){
if(err){
console.log(err);
} else{
console.log('Connected to mongodb!');
}
});
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);
var filter_CheckBoxSchema = mongoose.Schema({
name: String,
type: Boolean,
created: {type: Date, default: Date.now}
});
var Filter = mongoose.model('Store', filter_CheckBoxSchema);
fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
new Filter({
name: request.body.name,
type: request.body.gender,
}).save(function(err, doc){
if(err)
{
throw err;
}
else
response.send('Successfully inserted!!!');
});
});
index.html
<html>
<head>
<title>Please enter your details</title>
</head>
<body>
<h3>Please enter your details</h3>
<p>Please register below!!!</p>
<form action="filter.js" method="POST">
Name: <input type="text" name="Name" />
<br /><p></p>
Gender:
<br />
<input type="radio" name="gender"/> Male
<br />
<input type="radio" name="gender"/> Female
<p></p>
Interest: (Check all that apply)
<p>
</p>
<input type="checkbox" name="breakfast"/> Breakfast
<br/>
<input type="checkbox" name="Lunch"/> Lunch
<br />
<input type="checkbox" name="Evening Snacks"/> Evening Snacks
<br />
<input type="checkbox" name="Dinner"/> Dinner
<br />
<p></p>
<input type="submit" name="submit" value="Register!!!" />
</form>
</body>
</html>
Output:
C:\node\people discovery app>node filter.js
Connected to mongodb!
C:\node\people discovery app\filter.js:152
name: request.body.name,
^
ReferenceError: request is not defined
at C:\node\people discovery app\filter.js:152:9
at fs.js:271:14
at Object.oncomplete (fs.js:107:15)
It appears you don't completely grasp the asynchronous nature of javascript. Variables passed to a function only exist in that function's scope. See this commented code:
var express = require('express'),
http = require('http'),
fs = require('fs'),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/filter_CheckBoxSchema', function(err){
if(err){
console.log(err);
} else{
console.log('Connected to mongodb!');
}
});
//Lets read our html file only once, at the very beginning when we first start our nodejs process
fs.readFile('./index.html', function (err, html) {
//Now in here there are two variables which are accessible, `err` and `html`
if (err) {
throw err;
}
//Create our schema before starting server
var filter_CheckBoxSchema = mongoose.Schema({
name: String,
type: Boolean,
created: {type: Date, default: Date.now}
});
//And now the model as well
var Filter = mongoose.model('Store', filter_CheckBoxSchema);
//Now lets start our server
http.createServer(function(request, response) {
//The code here is called whenever a new http request is sent to the server
//There are two variables accessible here, one is `request` which contains
//data about the original request, while `response` is an object with methods
//allowing you to respond
//Here we check what kind of method the browser is using, if its POSTing
//data then we create a filter from the body
if (request.method == "POST") {
new Filter({
name: request.body.name,
type: request.body.gender,
}).save(function(err, doc){
if(err)
{
throw err;
}
else {
response.send('Successfully inserted!!!');
}
});
}
else {
//This must have been a GET request, lets just send `html` instead
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}
}).listen(8000);
});
Related
After fill information in below WebForm and submit my data ,I got undefined values under ms sql server records.
//my html file
<!doctype html>
<html lang="en">
<head>
<title>Employees</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<h1><center>Add a new Employee</center></h1><br>
<center>
<form action = "http://localhost:8080/api" method = "POST" enctype = "multipart/form-data">
<input type ="text" name ="first_Name" placeholder="Enter First Name"><br>
<br>
<input type ="text" name = "last_name" placeholder="Enter Last Name"><br>
<input type = "submit" value = "Submit">
</form><br>
</center>
<!-- Optional JavaScript -->
<script src="Node.js"></script>
</body>
</html>
This is my Node.js code :
//Initiallising node modules
var express = require('express');
var bodyPasrser = require('body-parser');
var sql = require('mssql');
var app = express();
//Body Parser to parse to JSON
app.use(bodyPasrser.json());
//CORS Middleware
app.use(function(req,res,next){
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Methods","GET,HEAD,POST,PUT,OPTIONS");
res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,contentType,Content-Type,Accept,Authorization");
next();
});
//Setting up server
var server = app.listen(process.env.PORT||8080,function(){
var port = server.address().port;
console.log("App now running on port ",port);
});
//setup database connection
var dbconfig = {
user:"sa",
password:"--------",
server : "localhost",
database: "Test"
};
// ConnectionPool
//connect to the database
var executeQuery = function(res,query){
sql.connect(dbconfig,function(err){
if(err){
console.log("there is a database connection error -> "+err);
res.send(err);
}
else{
// create request object
var request = new sql.Request();
// query to the database
request.query(query,function(err,result){
if(err){
console.log("error while querying database -> "+err);
res.send(err);
}
else{
res.send(result);
sql.close();
}
});
}
});
}
// Change execute query to accept parameters.
var executeQuery = function(res,query,parameters){
sql.connect(dbconfig,function(err){
if(err){
console.log("there is a database connection error -> "+err);
res.send(err);
}
else{
// create request object
var request = new sql.Request();
// Add parameters
parameters.forEach(function(p) {
request.input(p.name, p.sqltype, p.value);
});
// query to the database
request.query(query,function(err,result){
if(err){
console.log("error while querying database -> "+err);
res.send(err);
}
else{
res.send(result);
sql.close();
}
});
}
});
}
//POST API
app.post("/api", function(req , res){
var parameters = [
{ name: 'First_Name', sqltype: sql.NVarChar, value: req.body.First_Name},
{ name: 'Last_name', sqltype: sql.NVarChar, value: req.body.Last_name},
];
var query = "INSERT INTO test.dbo.name (First_Name,Last_name) VALUES ('" +req.body.First_Name+"','"+req.body.Last_name+"')";
executeQuery (res, query, parameters);
});
After display the records under SQL server I found that data I submitted , as "undefined" and it is not my data I submitted in the webform , please what is wrong in my code.
Please can give simple example in how to solve such case
thank you very much
There is typo in form data you are using,
var query = "INSERT INTO test.dbo.name (First_Name,Last_name) VALUES ('" +req.body.First_Name+"','"+req.body.Last_name+"')";
should be,
var query = "INSERT INTO test.dbo.name (First_Name,Last_name) VALUES ('" +req.body.first_Name +"','"+req.body.last_name+"')";
I'm trying to create a simple node server that sends emails with nodemailer
let app = require('express')();
app.use(require('body-parser').urlencoded());
const CONTACT_ADDRESS = 'email#email.com';
var mailer = require('nodemailer').createTransport({
service: 'mail.ee',
auth: {
user: 'test#test.com',
pass: 'password',
}
});
app.post('/contact', function(req, res) {
mailer.sendMail({
from: req.body.from,
to: '[CONTACT_ADDRESS]',
subject: req.body.subject || '[No subject]',
html: req.body.message || '[No message]',
}, function(err, info) {
if (err) return res.status(500).send(err);
res.json({success: true});
})
});
//Service is listening to port 3000
app.listen(3000, function(){
console.log("Service is running on port 3000...");
});
and the contact form is as follows:
<form method="post" action="http://localhost:3000/contact">
<label>Your e-mail</label>
<input type="text" name="from">
<label>Subject</label>
<input type="text" name="subject">
<label>Message</label>
<textarea name="body"></textarea>
<input type="submit" value="Submit">
</form>
When ever I press on submit button I get:
JSON.stringify(value); TypeError: Converting circular structure to
JSON
What does it mean? How can I overcome it?
res.send method trying to stringify your err object, but your err object cant be stringified, because not a standard error object. Try to output this err object to see and decide how to handle it.
For example you can use
if (err) return res.status(500).send(err.reason);
istead
if (err) return res.status(500).send(err);
I have been learning some Node.js and was trying to make a program where you enter a username and password and it is checked against a MySQL database. I don't know if I'm doing the whole authentication business correctly, but my question is this: Can you call a MySQL function after the start of the code (i.e. on some kind of function call).
Can you do a MySQL action on a function call?
I've looked on the internet and different Stack Overflow questions, but I still don't really understand. I may be missing a trick about what Node.js actually does though.
This is my code:
HTML:
<html>
<head>
<title>Basic User Information</title>
</head>
<body>
<form action="http://localhost:8888/user" method="POST">
Username: <input type="text" name="username"> <br>
Password: <input type="text" name="password"> <br></select>
<input type="submit" value="submit">
</form>
</body>
</html>
Node.js:
//import the express module
var express = require('express');
//import body-parser
var bodyParser = require('body-parser');
//store the express in a variable
var app = express();
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE authtest", function (err, result) {
if (err) throw err;
console.log("Database created");
});
con.query("CREATE TABLE users (username VARCHAR(255), password VARCHAR(255))", function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
//configure body-parser for express
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
//allow express to access our html (index.html) file
app.get('/index.html', function(req, res) {
res.sendFile(__dirname + "/" + "index.html");
});
//route the GET request to the specified path, "/user".
//This sends the user information to the path
app.post('/user', function(req, res){
response = {
username : req.body.username,
password : req.body.password
};
//this line is optional and will print the response on the command prompt
//It's useful so that we know what information is being transferred
//using the server
console.log(response);
//convert the response in JSON format
res.end(JSON.stringify(response));
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO users (username, password) VALUES (response.username, response.password)";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
});
//This piece of code creates the server
//and listens to the request at port 8888
//we are also generating a message once the
//server is created
var server = app.listen(8888, function(){
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
Edit:
Would I need to do this in another script? So, there is one for the initialisation of the page and one for inserting the data into the MySQL database?
as far i can see in your code you are setting a INSERT in the users table with the data passed by the form, and setting the server to respond before the action is complete so the page recieve the awnser anyway, but awnsering your question, YES, the actions you put in the "index.js" of your node server run as soon as it starts.
I have an error when I send data from client side (angular.js) to server side (node.js).
I created a form that the user insert data then my controller get the data and sent it to the server to save the data in mongoose and s3(amazon).
I must say that it works fine - I mean I can save all the information I need, I can see it in my DB and I can see the image on s3
but, I get an error : POST http://localhost:3000/upload 500 (Internal Server Error)
my html form:
<html ng-app="mymed">
<head>
<title>insert</title>
</head>
<body ng-controller="tryController">
<main>
<body>
<form class="form-group" enctype="multipart/form-data" method="POST" action="http://localhost:3000/upload">
<label for="inputEmail3" class="col-sm-2 control-label">Title:</label>
<input class="form-control" type="text" placeholder="Title" ng-model="Title" name="Title" required></input>
</div>
<div class="col-sm-10">
<br>
<input type="file" name="file" accept="image/*" ng-modle="file"></input>
</div>
</div>
<input type="submit" class="btn btn-default" name="send" ng-click="createInsert()"></input>
</form>
.....
<script src="js/appController.js"></script>
my controller:
mymedical.controller('tryController',['$scope','$http','$cookies', function($scope,$http,$cookies){
$scope.createInsert = function(){
var data = {};
data.Title = $scope.Title;
data.file = $scope.file;
$http.post('http://localhost:3000/upload', JSON.stringify(data)).then() //callback
}
}]);
sever side:
exports.saveDatatry=function(request, response){
console.log(request.body);
var file = request.files.file;
var hash = hasher();
var stream = fs.createReadStream(file.path)
var mimetype = mime.lookup(file.path);
console.log(stream);
var req;
if (mimetype.localeCompare('image/jpeg')
|| mimetype.localeCompare('image/pjpeg')
|| mimetype.localeCompare('image/png')
|| mimetype.localeCompare('image/gif')) {
req = client.putStream(stream, hash+'.png',
{
'Content-Type': mimetype,
'Cache-Control': 'max-age=604800',
'x-amz-acl': 'public-read',
'Content-Length': file.size
},
function(err, result) {
var savePerTry = new personal({
Title: request.body.Title,
file: req.url
});
savePerTry.save(function(error, result) {
if (error) {
console.error(error);
} else {
console.log("saved!");
response.redirect('http://localhost:8080/tryinsert.html');
};
})
});
} else {
console.log(err);
}
}
What I need to do?
Thanks,
Here's your problem:
function(err, result) {
var savePerTry = new personal({
Title: request.body.Title,
file: req.url
});
Every time you write something like:
function(err, result) {
then the very next line should be:
if (err) {
// ...
}
When you don't handle the errors you will get 500 internal server errors and you will not know what's wrong.
Always handle errors.
I'm fetching application details from the play store using the application package name.
The information that i want to print is not getting printed on the web page and html as well.
the node js code (server .js) is
var http = require('http');
var fs = require('fs');
var formidable = require("formidable");
var util = require('util');
var googlePlaySearch = require('google-play-search');
var appName = " ";
var gameData = " ";
var server = http.createServer(function (req, res) {
if (req.method.toLowerCase() == 'get') {
displayForm(res);
} else if (req.method.toLowerCase() == 'post') {
processAllFieldsOfTheForm(req, res);
}
});
function displayForm(res) {
fs.readFile('form.html', function (err, data) {
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': data.length
});
res.write(data);
res.end();
});
}
function processAllFieldsOfTheForm(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
//Store the data from the fields in your data store.
//The data store could be a file or database or any other store based
//on your application.
res.writeHead(200, {
'content-type': 'text/plain'
});
var url = fields;
googlePlaySearch.fetch(url, function (err, gameData) {
console.log(gameData);
appName = gameData;
res.write('received the data:\n\n');
res.end(util.inspect({
fields: appName,
})); //for end
}); //for parse
});
}
server.listen(1185);
console.log("server listening on 1185");`enter code here`
and the html code is(form.html) :
<html>
<body>
<form action="" method="post" enctype="multipart/form-data">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="PACKAGE NAME" />
<br />
<label for="email">Email:</label>
<input type="submit" value="SUBMIT" />
</fieldset>
</form>
</body>
</html>
Please help me with the code.
Thank you.