I am trying to write a simple server.js in Node, that posts form data from my html file, into MySQL. But I am getting a Syntax error. I have posted the code and error below. I'm struggling to resolve this issue.
Error
http://localhost:3000/submit
Error: No default engine was specified and no extension was provided.
at new View (C:\website\node_modules\express\lib\view.js:61:11)
at Function.render (C:\website\node_modules\express\lib\application.js:570:12)
at ServerResponse.render (C:\website\node_modules\express\lib\response.js:1008:7)
at C:\website\index.js:21:9
at Layer.handle [as handle_request] (C:\website\node_modules\express\lib\router\layer.js:95:5)
at next (C:\website\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\website\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\website\node_modules\express\lib\router\layer.js:95:5)
at C:\website\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\website\node_modules\express\lib\router\index.js:335:12)
index.html
<form action="/submit" method="post">
<input id="name" type="text" name="name" placeholder="Type your name...">
<input id="message" type="text" name="message" placeholder="Type message...">
<input class="submit_message" type="submit" value="Send">
</form>
index.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public'));
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mywebsite"
});
connection.connect();
app.get('/submit',function(req,res) {
res.render('index');
});
app.post('/submit',urlencodedParser, function(req, res, next) {
console.log(req.body.name);
console.log(req.body.message);
connection.connect(function(err) {
if (err) throw err;
console.log("connected");
var sql = "INSERT INTO `users` (`name`,`message`) VALUES ('" + req.body.name + "', '" + req.body.message + "')";
con.query(sql, function(err, result) {
if(err) throw err;
console.log("table created");
});
});
res.render('index', {title: 'Express'});
});
connection.end();
app.listen(3000, function () {
console.log('Listening on port 3000');
});
MySQL database
This is how my database should look like
I have refactored your code, As per question specified. for ex- You need to mention all our static content inside public directory (i.e your index.html), Also you have done syntax error ie- you have written con.query(sql, function(err, result) instead of connection.query(sql, function (err, result), instead of rendering index.html file as you did res.render('index', {title: 'Express'}); its better you send the file to your public/index.html res.sendFile('public/index.html', { root: __dirname }); as specified by #Pogrindis
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mywebsite"
});
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public'));
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.render('index.html');
});
app.post('/submit', urlencodedParser, function (req, res) {
console.log("Im here");
console.log(req.body.name);
console.log(req.body.message);
connection.connect(function (err) {
if (err) throw err;
console.log("connected");
var sql = "INSERT INTO `users` (`name`,`message`) VALUES ('" + req.body.name + "', '" + req.body.message + "')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("table created");
});
});
res.sendFile('public/index.html', { root: __dirname });
});
app.listen(3000, function () {
console.log('Listening on port 3000');
});
please follow the file path as :
I am successfully able to persist the data to my DB which has been entered from input text box(name, message) in index.html.
Happy coding !!
Related
what's the fault in this code
const express = require('express')
const app = express()
const port = 3000
var mysql = require('mysql');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var md5 = require('md5');
//MySQL Connection
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "school"
});
con.connect(function(err){
if(err) throw err;
console.log("Connected!");
});
app.use(bodyParser.json()); //support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true})); // support encoded bodies
app.get('/', (req,res) =>{
con.query("SELECT * FROM users", function(err, rows, fields){
if(err) throw err;
res.send("The first user is: " + rows[0].email);
});
});
app.post('/', function(req,res){
con.query("SELECT * FROM users WHERE name = ? AND password = ?" , [req.body.name, md5(req.body.password)] , function(err, result, fields){
if(err) throw err;
if(result.length > 0){
if(result)
res.send({ status:1, message: result});
} else{
res.send({ status:0, message: "error in username or password"});
}
});
});
app.listen(port, () => console.log('Example app listening at http://localhost:${port}'))
I get this error in cmd every time I use postman to try post:
Error: Illegal argument undefined
at module.exports (C:\\hsoub\\api\\node_modules\\md5\\md5.js:152:13)
at C:\\hsoub\\api\\index.js:50:87
at Layer.handle \[as handle_request\] (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\layer.js:95:5)
at next (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\route.js:144:13)
at Route.dispatch (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\route.js:114:3)
at Layer.handle \[as handle_request\] (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\layer.js:95:5)
at C:\\hsoub\\api\\node_modules\\express\\lib\\router\\index.js:284:15
at Function.process_params (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\index.js:346:12)
at next (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\index.js:280:10)
at urlencodedParser (C:\\hsoub\\api\\node_modules\\body-parser\\lib\\types\\urlencoded.js:100:7)
what's the problem?
My app.js entire codes:
var express = require("express");
var app = express();
var port = 3000;
app.listen(port, () => {
console.log("Server listening on port " + port);
});
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/node-demo", { useNewUrlParser: true, useUnifiedTopology: true });
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
var nameSchema = new mongoose.Schema({
firstName: String,
lastName: String
});
var User = mongoose.model("User", nameSchema);
app.post("/addname", (req, res) => {
});
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/addname", (req, res) => {
app.post("/addname", (req, res) => {
var myData = new User(req.body.firstName, req.body.lastName);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
})
});
This is my index.html file
<!DOCTYPE html>
<html>
<head>
<title>Intro to Node and MongoDB
</title>
</head>
<body>
<h1>Into to Node and MongoDB</h1>
<form method="post" action="/addname">
<label>Enter Your Name</label><br>
<input type="text" name="firstName" placeholder="Enter first name..." required>
<input type="text" name="lastName" placeholder="Enter last name..." required>
<input type="submit" value="Add Name">
</form>
</body>
<html>
After writing my code I open my mongod server than start mongo in other terminal then I run my app.js it worked properly it create server localhost:3000 then I went to my host I add my name in form and then submit, but it doesn't add to my database
Why this is not working?
My form data doesn't stored in my mongodb database. Please help me!
I think the body-parser library is deprecated on express 4 and later versions.
please use
app.use(express.json())
instead of body=parser.
not need to call any npm packages for parsing data from the form.
Here is the issue:
var myData = new User(req.body.firstName, req.body.lastName);
you have to pass an object to new User
var myData = new User( { firstName:req.body.firstName, lastName:req.body.lastName } );
i think i know what is wrong.
change app.use("/"... to app.get("/"...
bacause use handles all requests including POST. so when you send any request it sends the html file again and kills any other process.
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
I think you are not passing data correctly in the user model.
app.post("/addname", (req, res) => {
// make sure your request object is getting the same properties
var myData = new User(req.body.firstName, req.body.lastName);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
As you updated the code for form, lastName is the fieldName. You should make the changes in the schema object too.
Also, Please check the request headers that comes in if it is of Accept:multipart/form-data then the bodyParser won't work instead you should use multer.
Some useful body parsers that you might need to consider if needed.
form-data: multer
x-www-form-urlencoded: express.urlencoded()
raw: express.raw()
json: express.json()
text: express.text()
Updated app.js file:
var express = require("express");
var app = express();
var port = 3000;
app.listen(port, () => {
console.log("Server listening on port " + port);
});
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/node-demo", { useNewUrlParser: true, useUnifiedTopology: true });
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
var nameSchema = new mongoose.Schema({
firstName: String,
lastName: String
});
var User = mongoose.model("User", nameSchema);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/addname", (req, res) => {
var myData = new User(req.body.firstName, req.body.lastName);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
Note: you have added two extra routes with same route handler, I have just removed it. Update this file in your project and run it.
I am new to web development in general. I am trying to insert and find documents in a local mongoDB database through GET and POST requests. I am doing this with a Node.js/Express web server. I've managed to get something working, but I'm not sure if I'm doing the right thing.
First, I wrote client.html to send POST requests.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Client</title>
</head>
<body>
<p>Insert something into the database:</p>
<form action="/items" method="POST">
<input type="text" name="item">
<button type="submit">Submit</button>
</form>
</body>
</html>
After reading the mongoDB documentation for Node.js, I decided to write my Node.js server as follows, putting all my routes under one connection (approach 1):
const express = require("express");
const app = express();
const port = 5000;
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, { useUnifiedTopology: true });
app.use(express.urlencoded({ extended: true }));
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db("my_db");
const itemsCollection = db.collection("items");
app.get("/", function(req, res) {
res.sendFile(__dirname + "/client.html");
});
// GET request - find documents
app.get("/items", function(req, res) {
itemsCollection.find().toArray(function(err, docs) {
assert.equal(null, err);
console.log(docs);
});
});
// POST request - insert document
app.post("/items", function(req, res) {
itemsCollection.insertOne(req.body, function(err, result) {
assert.equal(null, err);
res.redirect("/");
});
});
app.listen(port, function() {
console.log(`Listening on port: ${port}`);
});
});
However, I've also seen people create a new connection for every route, which would be something like this (approach 2):
const express = require("express");
const app = express();
const port = 5000;
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, { useUnifiedTopology: true });
app.use(express.urlencoded({ extended: true }));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/client.html");
});
// GET request - find documents
app.get("/items", function(req, res) {
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db("my_db");
const itemsCollection = db.collection("items");
itemsCollection.find().toArray(function(err, docs) {
assert.equal(null, err);
console.log(docs);
});
});
});
// POST request - insert document
app.post("/items", function(req, res) {
client.connect(function(err) {
assert.equal(null, err);
const db = client.db("my_db");
const itemsCollection = db.collection("items");
itemsCollection.insertOne(req.body, function(err, result) {
assert.equal(null, err);
res.redirect("/");
});
});
});
app.listen(port, function() {
console.log(`Listening on port: ${port}`);
});
Both approaches successfully complete the database operations. I would like to know:
Which of these approaches (if any) are recommended, and why?
Should I be calling client.close() anywhere in my server code?
Any help is appreciated, thanks!
I am trying to make a post request to my first app, but every time I go to make the post, it gives me this error: TypeError: db.getConnection is not a function
I have tried all of stack overflows suggestions, but I still can't seem to get it to work after messing around with the code for the last 2 days. I am a beginner so please forgive me, but here is what my code looks like...
my db.js looks like this....
var mysql = require('mysql');
var mainDb = mysql.createPool({
host : process.env.mysql_host,
user : process.env.mysql_user,
password : process.env.mysql_pwd,
database : process.env.mysql_db
});
exports.getConnection = function(callback) {
mainDb.getConnection(function(err, connection) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
callback(err, connection);
});
};
and my register.js code looks like this...
var express = require('express');
var router = express.Router();
var db = require(__dirname, 'models/db');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
router.get('/register', function(req, res, next) {
res.render('register', { title: 'Register for a free account' });
});
router.post('/register', function(req, res) {
var input = JSON.parse(JSON.stringify(req.body));
var today = new Date();
var users = {
"username": req.body.username,
"email":req.body.email,
"password":req.body.password,
"created":today,
"modified":today
};
db.getConnection(function(err, connection) {
connection.query('INSERT INTO users SET ? ', users, function(err, result) {
connection.release();
if (err) { return console.error(err); }
});
});
res.redirect('/index');
});
module.exports = router;
I don't know if my app.js is relevant for this question, but it looks like this...
const express = require('express');
http = require('http');
path = require('path');
session = require('express-session');
app = express();
mysql = require('mysql');
bodyParser = require('body-parser');
db = require(__dirname, 'models/db')
var index = require('./routes/index');
var register = require('./routes/register');
app.use('/', index);
app.use('/', register);
var engine = require('ejs-mate');
app.engine('ejs', engine);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
var server = http.createServer(app);
var port = 8995;
server.listen(port);
module.exports = app;
When I start app.js I get no errors, only when I make my post request from my form, the error shows up in my browser. Please help!
At db.js you are exporting only a function. But at register.js, you are trying to use db as if it was an object.
To solve your problem, at db.js, just export an object, instead of a function:
function getConnection(callback) {
mainDb.getConnection(function(err, connection) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
callback(err, connection);
}
module.exports = { getConnection };
You don't need use getConnection method only exports the pool, according the documentation.
https://github.com/mysqljs/mysql
I am setting up a node js server and in my output of req.body i keep getting undefined, i am trying to requesting SQL data from a form Get request
I am able to retrieve other queries just none involving req.body
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public'));
app.use(express.static(__dirname + '/public'));
app.get('/submit',urlencodedParser,function (req, res){
connection.connect(function (err) {
if (err) throw err;
console.log(req.body.lname);
var exist = req.body.lname;
var sql = "SELECT * FROM users WHERE lname= '" + exist + "'";
connection.query(sql, function(err,result) {
if (err) throw err;
console.log(result);
console.log(exist);
console.log(req.body.lname);
console.log("hello");
console.log(result);
});
});
'
output:
undefined
[]
undefined
undefined
hello
[]
Get request doesn't carry the req.body object.
You will have to use either req.query or req.params to pass your data or transform your get into post.
app.post('/submit', function(req, res) {
connection.connect(function (err) {
if (err) throw err;
var exist = req.body.lname;
var sql = "SELECT * FROM users WHERE lname= '" + exist + "'";
connection.query(sql, function(err,result) {
if (err) throw err;
else console.log(result);
});
});