I'm sure this has already been answered but I can't find the exact question I'm looking for.
I have an ejs file that has this for the form.
<form action="" method="POST">
<div class="input-group">
<input type="text" class="form-control" name="userSearchInput" placeholder="Enter the id of the product you would like to buy" aria-label="Recipient's username" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-outline-secondary" id="searchBTN" type="submit"><i class="fas fa-cart-plus mr-2"></i>Add to Cart</button>
</div>
</div>
</form>
On the node side in my app.js file, I've installed and downloaded both express and body-parser and done the requisite require function.
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
I've set up my middleware for body-parser here:
// middleware for bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
Then, to get the content of what the user types into the input text box, I'm using this:
app.post('/', function(req, res) {
var item = req.body.userSearchInput;
console.log(item);
});
This is my first time using app.post and since nothing is being console logged- I'm not sure where I'm going wrong.
full app.js file
var express = require('express');
var path = require('path');
var http = require('http');
var mysql = require('mysql');
var bodyParser = require('body-parser');
var nodemon = require('nodemon');
var app = express();
var port = process.env.PORT || 3000;
// setting up views
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
// middleware for bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// create connection to mySQL db
var connection = mysql.createConnection ({
host : 'localhost',
user : 'root',
password : 'root',
database : 'bamazon'
});
// initialize connection
connection.connect();
// run db query and print items to index html home page
connection.query('SELECT * from products', function (error, results) {
if (error) throw error;
console.log(results);
app.get('/', function(req, res){
res.render('index', {list: results});
})
});
app.post('/', function(req, res) {
var item = req.body.userSearchInput;
console.log(item);
});
// setting up listen for server function
app.listen(port, function (err) {
if (err) throw err;
console.log("Server is running on port " + port);
});
use
<form action="/" method="post">
Firstly add form action in your ejs file like action="/search".Step 2: try with app.post('/search'
Works fine i just commented out db connections only.
may be try this app.js file with new express project.
Run command node app instant of npm start
var express = require('express');
var path = require('path');
var http = require('http');
var bodyParser = require('body-parser');
// var nodemon = require('nodemon');
// var mysql = require('mysql');
var app = express();
var port = process.env.PORT || 3000;
// setting up views
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
// middleware for bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
/*
create connection to mySQL db
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'bamazon'
});
// initialize connection
connection.connect();
// run db query and print items to index html home page
connection.query('SELECT * from products', function (error, results) {
if (error) throw error;
console.log(results);
});
*/
app.get('/', function (req, res) {
res.render('index', { list: [], title:"salman" });
})
app.post('/', function (req, res) {
var item = req.body.userSearchInput;
console.log(item);
});
// setting up listen for server function
app.listen(port, function (err) {
if (err) throw err;
console.log("Server is running on port " + port);
});
Related
I'm trying to make a simple file upload system but everytime I submit my uploaded file I get a 404 error. I've tried various different names and paths but all of them fail instantly. When I press submit, the browser tries to redirect to /upload then returns the 404 error. I'm new to node.js so it may as well be very simple to solve but I couldn't find it.
I've tried 2 different modules, formidable and express-fileupload. Both return the same error.
./views/test2.ejs
<html>
<head>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="filetoupload"><br>
<input type="submit">
</form>
</body>
./routes/test2.js
var express = require('express');
var router = express.Router();
var http = require('http');
var formidable = require('formidable');
router.get('/', function (req, res, next) {
res.render('test2');
res.sendFile(__dirname + '/test2.ejs');
});
router.post('/upload', function (req, res, next) {
var form = new formidable.IncomingForm();
form.parse(req);
form.on('fileBegin', function (name, file) {
file.path = __dirname + '/uploads/' + file.name;
});
form.on('file', function (name, file) {
console.log('Uploaded ' + file.name);
});
res.sendFile(__dirname + '/test2.ejs');
});
module.exports = router;
./app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect("REDACTED", function(err,db){
if(!err){
console.log("Connected");
}
});
var index = require('./routes/index');
var users = require('./routes/users');
var login = require('./routes/login');
var form = require('./routes/form');
var buttonrelay = require('./routes/buttonrelay');
var tesekkurler = require('./routes/tesekkurler');
var test = require('./routes/test');
var test2 = require('./routes/test2');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//app.use(expressLayout);
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressValidator());
// Express Session
app.use(session({
secret: REDACTED,
saveUninitialized: true,
resave: true
}));
app.use('/', index);
app.use('/users', users);
app.use('/login', login);
app.use('/form', form);
app.use('/buttonrelay', buttonrelay);
app.use('/tesekkurler', tesekkurler);
app.use('/test', test);
app.use('/test2', test2);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
you used app.use('/test2', test2); for the /upload routing
So form action should be "/test2/upload"
var express = require("express");
var app = express();
var path = require("path");
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydatabase"
});
app.get('/',function(req,res)
{
res.sendFile(path.join(__dirname+'/app.html'));
});
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'js');
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function(req,res)
{
res.render('index');
});//inserting data
app.post('/insert', function(req,res)
{
pool.getConnection(function(error,conn)
{
var queryString = "insert into customers(firstName,lastName)values('"+req.body.fname+"','"+req.body.lname+"')";
conn.query(queryString,function(error,results)
{
if(error)
{
throw error;
}
else
{
res.send('Inserted Successfully!')
}
});
conn.release();
});
});//server starting
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
app.listen(2000);
console.log("Running at Port 2000")
});
I am making a web page in which I want to insert data by the user so I have created this code in node.js to perform data tranfer but it is showing
No default engine was specified and no extension was provided.
What could be the problem?
i got my mistake its in app.set('view engine', 'js');
it should be app.set('view engine', 'ejs');
but when i fixed it a new error has arrived and that is
Failed to lookup view "index" in views directory "D:\nodejs/views"
I have a very simple html form, and express server, but I can't make the routing work. I always get "Cannot Post" message. What did I miss?
var express = require('express');
var bodyparser = require('body-parser');
var path = require('path');
var app = express();
app.use(express.static("public"));
app.use(express.bodyParser());
app.get("/", function(req, res){
res.sendFile(path.join(__dirname+"/index.html"));
});
app.post("/sendform", function(req, res){
res.send('You sent the name "' + req.query.user + '".');
});
app.listen(3000, function(){
console.log("Server is running at port: 3000");
});
<form method="post" action="http://localhost:3000/sendform">
<input type="text" name="username" />
<input type="submit" value="küldés" />
</form>
With express 4.15.3, you have to use the body parser a bit differently.
I changed your code to this and I was able to post to it:
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
app.use(express.static("public"));
//app.use(express.bodyParser());
app.use(bodyParser.json({
limit: "10mb"
}));
app.use(bodyParser.urlencoded({
limit: "10mb",
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname + "/index.html"));
});
app.post("/sendform", function (req, res) {
res.send('You sent the name "' + req.query.user + '".');
});
app.listen(3000, function () {
console.log("Server is running at port: 3000");
});
I have used below code. i have run the file and there are no errors. But the server 192.123.1.134:5001 shows 'No data received'.
Kindly help me to find out error in the code.
express = require('express');
app = express();
config = require('./config/database.js');
var path = require('path');
//app.set('views', __dirname + '/views')
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'jade');
router = express.Router();
var routes = require('./user/index');
var admin = require('./user/user');
app.use('/', routes);
app.use('/user', admin);
http = require('http');
server = http.createServer(app);
server.listen('5001','192.123.1.134', function(){
console.log('%s: Node server started on %s:%d ...',Date(Date.now() ));
});
index.js
var User = require('../model/user.js');
router.get('/', function(req, res, next) {
User.getuserdetails(function(data) {
res.render('user', {
title: 'Welcome',
result : data
});
});
//res.render('index', { title: 'welcome' });
});
module.exports = router;
user.js (model)
var connection =require("../config/database.js");;
router.getuserdetails = function (req,res){
var result = connection.query('SELECT * FROM table1','', function (err, rows) {
if (err) throw err
});
}
module.exports = router;
database.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'aaa',
database : 'my_db'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
Just give the localhost/127.0.0.1 in the IP address part.
You can access it in LAN using your IP address 192.123.1.134.
server.listen('5001','127.0.0.1', function(){
console.log('%s: Node server started on %s:%d ...',Date(Date.now() ));
});
I want to simply display usernames and age on the webpage using Express Node.js and Mongoose/
The view should get updated on the left while the form is at the right. Refer this image.
Below is my users.js (/users route) followed by html of the form.
Bodyparser has been included in app.js of this application.
On clicking submit, 404 not found is thrown.
Refer this error image
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.render('userview');
});
router.post('#', function(req, res, next) {
//User is the model created in app.js of this project
var newUser = userModel({
name:req.body.name,
age: req.body.age
});
console.log(newUser);
// save the user
newUser.save(function(err) {
if (err) throw err;
console.log('User created!');
});
});
module.exports = router;
<form method="post">
Name:
<input type="text" name="name"><br><br>
Age:
<input type="number" name="age"><br><br>
<input type="submit" value="Submit">
</form>
Here is my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var applist = require('./routes/applist');
var mongoose=require('mongoose');
var app = express();
//set database connection
mongoose.connect('mongodb://localhost:27017/users');
mongoose.connection.on('error',function(){
console.log('MongoDB Connection Error. Please make sure that MongoDB is running');
process.exit(1);
});
mongoose.connection.once('open',function(callback){
console.log('Connected to Database');
});
var userSchema = new mongoose.Schema({
name:{type:String,uppercase:true},
age:Number
},{collection:'userlist'});
//make model
var userModel = mongoose.model('userModel',userSchema);
app.get('/users', function(req, res, next) {
userModel.find({},function(err,userModel){
res.render('userview',{userlist:userModel});
})
});
module.exports = userModel;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
userModel is present in app.js
On the view change
name = "fullname" to name="name"
userview
<form method="post">
Name <input type="text" name="name"><br><br>
Age<input type="number" name="age"><br><br>
<input type="submit" value="Submit">
</form>
First of all, to use req.body you need to use body-parser or busboy, connect-busboy, multiparty, connect-multiparty, formidable, multer etc. - see:
https://github.com/expressjs/body-parser
Also, what is this route supposed to be:
router.post('#', function(req, res, next) {
This character is not valid in the URL path amd needs to be URL-encoded on the client side to work. Are you sure that this is the route your need?
If you are thinking about the fragment part of the URL (as in http://host/path#fragment) then it is not sent during the HTTP request at all. See:
https://en.wikipedia.org/wiki/Fragment_identifier