I try to use multer to store locally files. I just want to run the sample but my app.post route is not triggered.
here is my simple code (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 multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 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.get("/", function(req, res){
res.render("index", { title: 'Express' });
});
app.get("/upload", function(req, res) {
res.render("upload");
});
app.post('/upload', upload.single('upl'), function (req, res) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
console.log(req.file);
})
...// regular code generated by express
and my jade view is ad follow (upload.jade)
extends layout
block content
h1= title
p Welcome to upload form
form(method="post",enctype="multipart/form-data",action="/upload")
p
input(type="text",name="title", placeholder="title")
p
input(type="file",name="upl")
p
input(type="submit")
There is something I am missing but don't see what.
Thx
Ok, sorry for asking this question.
I was focused on the js file where the indentation wasn't correct in my jade file. form was empty. All p's must be inside the form.
Related
So I'm developing a chat server using expressjs and socketio and decided to create an admin where backend built in with the node chat server itself.
const express = require("express");
const app = express();
const port = 3700;
let io = require('socket.io').listen(app.listen(port));
let socketList = io.sockets.server.eio.clients;
const path = require('path');
const bodyParser = require('body-parser');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/login', function(req, res) {
res.render('login', { title: 'Login | Argos Chat' });
});
app.post('/login', function(req, res) {
console.log(req.body);
});
So upon login data submission, I tried to display the post data from the login form but it returns me an empty object {}
console.log(req.body);
Tried to do req.params but same result .Any help, ideas is greatly appreciated.
I tried running your code and its working fine. Maybe the way you are calling the API is not right
To support content-type: x-www-form-urlencoded you should use
app.use(bodyParser.urlencoded({ extended: true }));
and to support content-type: application/json you should use
app.use(bodyParser.json());
I think you are using form-data, for that neither of these will work. For that you may want to use formidable package. We should use form-data content type only when we are sending any images/file.
And body-parser has been merged with express. You can directly use this now
app.use(
express.json(),
express.urlencoded({ extended: false })
);
I think this might be a right solution for your problem, as everything seems to be right in your code, the error might be caused by the way you are calling the API and you are setting the headers:
https://stackoverflow.com/a/25904070/12090205
const express = require("express");
const app = express();
const port = 3700;
let io = require('socket.io').listen(app.listen(port));
let socketList = io.sockets.server.eio.clients;
const path = require('path');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/login', function(req, res) {
res.render('login', { title: 'Login | Argos Chat' });
});
app.post('/login', function(req, res) {
console.log(req.body);
});
I checked Its Working.
I've just started learning Node/Express and am currently trying to add a new page and route for it. I'm currently getting a 500 error.
My code is as follows (I've deleted the bits that aren't relevant):
app.js
var express = require('express');
var index = require('./routes/index');
var upload = require('./routes/upload');
var app = express();
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/upload', upload);
app.use(express.static('public'));
upload.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('upload', { title: 'Upload Image' });
});
module.exports = router;
All the routing is correct. I tried replacing the code in upload.js with the code in index.js (that comes with express-generator), and that worked.
I am a newbie to use express and as a result am bungling my way through making this web app.
I have my routes in a different file called route.js inside a module.export, and I manage all this inside app.js and I want to be able to serve a HTML page and keep it in the module. I've done so using sendFile but it doesn't serve the CSS and JS as well. What can I do to fix this?
app.js
//setup
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 app = express();
var port = process.env.PORT || 3000;
var mongoose = require('mongoose');
var flash = require('connect-flash');
var passport = require('passport');
var session = require('express-session');
var path = require('path');
//db
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
require('./config/passport')(passport);
// view engine setup
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');
app.set('view engine', 'ejs');
//routes
//app.use('/', index);
//app.use('/users', users);
// 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')));
//passport
app.use(session({secret: 'secret'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
//routes
require('./app/routes.js')(app, passport);
// 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;
//launch
app.listen(port);
console.log('Website starting on port ' + port);
routes.js
module.exports = function(app,passport) {
...
//--timesheet section---
app.get('/timesheet', function(req, res) {
var path = require('path');
res.sendFile(path.resolve('public/timesheet.html'));
});
...
}
You want to use a view engine and a static directory. You have some of the code already.
Your view engine using .ejs:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
And you can define your static and specify a path prefix:
app.use('/assets', express.static(path.join(__dirname, 'public')));
In your views directory, put your htmls with .ejs extension, such as timesheet.ejs. You can then create an assets directory for your css/js/image files and reference them in your timesheet.ejs using /assets/style.css.
Finally, in your route, you'll want to render the template:
res.render('timesheet')
I have the following folder structure:
bin
controllers
models
node_modules
public
routes
views
app.js
package.json
As I am new to node.js and express.js, I would like to know how to render .ejs file from the controller file. Currently, my code looks like:
//controllers/login.js
module.exports = {
getLoginPage: function (req, res) {
res.render('login-form');
}
};
//routes/login.js
var login = require('../controllers/login');
module.exports = function(app){
app.get('/', login.getLoginPage);
};
//app.js
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser'); //parses information from POST
var stylus = require('stylus');
var validator = require('express-validator');
var session = require('express-session');
var app = express();
require('./routes/login')(app);
// 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(validator());
app.use(cookieParser());
app.use(stylus.middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({secret: 'max', saveUninitialized: false, resave: false}));
// 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;
In my controller, if I write res.send("Hello");, it prints but I want the entire .ejs file to show up on my browser. How is this possible?
Also, if I render the .ejs from my routes, it's displaying properly but not from the controllers.
//error
Error: Failed to lookup view "error" in views directory "C:\node\folder-name\views"
at EventEmitter.render (C:\node\folder-name\node_modules\express\lib\application.js:580:17)
at ServerResponse.render (C:\node\folder-name\node_modules\express\lib\response.js:971:7)
at C:\node\folder-name\app.js:60:7
at Layer.handle_error (C:\node\folder-name\node_modules\express\lib\router\layer.js:71:5)
at trim_prefix (C:\node\folder-name\node_modules\express\lib\router\index.js:315:13)
at C:\node\folder-name\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\node\folder-name\node_modules\express\lib\router\index.js:335:12)
at next (C:\node\folder-name\node_modules\express\lib\router\index.js:275:10)
at Layer.handle_error (C:\node\folder-name\node_modules\express\lib\router\layer.js:67:12)
at trim_prefix (C:\node\folder-name\node_modules\express\lib\router\index.js:315:13)
Thanks
Change your view path to this:-
app.set('views',path.join(__dirname+'/views/'));
then in controller you can simply use
//assuming hello.ejs is in your view folder
response.render('hello.ejs');
and if you have folders in views folder then use
response.render('error/404.ejs');
First, you need to set the rendering engine for views:
app.set('view engine','ejs');
You need to set the view engine to ejs :
app.set('view engine', 'ejs')
Docs
Try the following:
var path = require('path');
res.render(path.resolve('./views/error'))
I have made a form.On successful submission of the form I wanted to redirect my page to thankyou page(another ejs) view. Somehow if I am using res.redirect() it is not working but on using res.send('Thank you') it is working fine.
Below is the code of 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 mongoose = require('mongoose');
var routes = require('./routes/index');
var users = require('./routes/users');
var thankyou = require('./routes/thankyou');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
var engine = require('ejs-locals');
app.engine('ejs', engine);
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')));
mongoose.connect('mongodb://localhost/my-data');
app.use('/', routes);
app.use('/users', users);
app.use('/thankyou', thankyou);
var Schema = new mongoose.Schema({
name : String,
email : String
});
var user = mongoose.model('Users', Schema);
app.post('/test',function(req,res){
new user({
email : req.body.email,
name : req.body.name
}).save(function(err, doc){
if(err){
console.log('boo');
}
else{
console.log('innner');
res.redirect("/thankyou");
res.end();
}
})
})
thankyou route:
var express = require('express');
var router = express.Router();
router.get('/thankyou', function(req, res) {
res.render('thankyou');
});
module.exports = router;
thankyou view
<h2>THANKS/h2>
This:
app.use('/thankyou', thankyou);
...combined with this:
router.get('/thankyou', ...);
...creates a route that matches /thankyou/thankyou.
Instead, you probably want this:
router.get('/', ...);