Conflict with express.js - Cannot get my static files - javascript

Hello, I'm using express.js to make a webapp to buy tickets. So I have a page that direct a person to a info about the party, however, when I try load the static files to this page, the express.js cannot get.
On console view I saw that a new directory, with name of the path for the url, is setting before of static folder.
My app.js file:
var express = require('express');
var path = require('path');
var teste = require('./db/teste.json')
var app = express();
var list = Object.keys(teste).map( (value) => teste[value]);
app.set('view engine', 'jade');
app.set('views', (__dirname + '/views'));
app.use('/static', express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('index')
});
app.get('/login/', function(req, res){
res.render('login')
});
app.get('/dash/:title?', function(req, res){
var title = req.params.title;
if(title === undefined){
res.status(503);
var isDash = true;
res.render('dash', {db: list, isDash: isDash});
}else{
var festa = teste.title;
res.render('party', {db: festa, isDash: isDash});
}
});
The console view:
PS: Only happens in this page.
Thank you!

Because the page is localhost:3000/dash/name-of-party, static resources that use relative URL will be referenced relative to that page, so, e.g.:
<img src="static/something.jpg">
Will be retrieved with a full url of: http://localhost:3000/dash/static/something.jpg. Instead you could use src="/static/something.jpg" (notice the leading slash) and it may work. Just to confirm this is the issue you could add:
app.use('/dash/static', express.static(path.join(__dirname, 'public')));
Right after the existing line that maps static resources.

Related

ENOENT: no such file or directory

I made a small project with authentication based on this example https://github.com/lyndachiwetelu/using-passport-with-sequelize-and-mysql. I had a mistake "Error: ENOENT: no such file or directory, open 'C:\Users\user\Desktop\using-passport-with-sequelize-and-mysql-master\app\views\layouts\main.hbs'"
But I did not point this way anywhere, it's strange. I beg you to help me, guys <3
I've alrready tried to make such way, and create such file(main.hbs), but in this case i can't reach another pathes ( dashboard, signin ). In this case they all have the same html-code from main.hbs
server.js :
var express = require('express')
var app = express()
var passport = require('passport')
var session = require('express-session')
var bodyParser = require('body-parser')
var env = require('dotenv').config()
var exphbs = require('express-handlebars')
//For BodyParser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// For Passport
app.use(session({ secret: 'keyboard cat',resave: true,
saveUninitialized:true})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
//For Handlebars
app.set('views', './app/views')
app.engine('hbs', exphbs({extname: '.hbs'}));
app.set('view engine', '.hbs');
app.get('/', function(req, res){
res.send('Welcome to Passport with Sequelize');
});
//Models
var models = require("./app/models");
//Routes
var authRoute = require('./app/routes/auth.js')(app,passport);
//load passport strategies
require('./app/config/passport/passport.js')(passport,models.user);
//Sync Database
models.sequelize.sync().then(function(){
console.log('Nice! Database looks fine')
}).catch(function(err){
console.log(err,"Something went wrong with the Database Update!")
});
app.listen(5000, function(err){
if(!err)
console.log("Site is live"); else console.log(err)
});
app/routes/auth.js :
var authController = require('../controllers/authcontroller.js');
module.exports = function(app,passport){
app.get('/signup', authController.signup);
app.get('/signin', authController.signin);
app.post('/signup', passport.authenticate('local-signup', { successRedirect: '/dashboard',
failureRedirect: '/signup'}
));
app.get('/dashboard',isLoggedIn, authController.dashboard);
app.get('/logout',authController.logout);
app.post('/signin', passport.authenticate('local-signin', { successRedirect: '/dashboard',
failureRedirect: '/signin'}
));
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/signin');
}
}
app/contrroller/authcontroller.js :
var exports = module.exports = {}
exports.signup = function(req,res){
res.render('signup');
}
exports.signin = function(req,res){
res.render('signin');
}
exports.dashboard = function(req,res){
res.render('dashboard');
}
exports.logout = function(req,res){
req.session.destroy(function(err) {
res.redirect('/');
});
}
In folder "app\views" only files with html-code, so i don't show them.
I still can't understand where program take this path \app\views\layouts\main.hbs
PROBLEM: Error: ENOENT: no such file or directory, open 'C:\Users\user\Desktop\using-passport-with-sequelize-and-mysql-master\app\views\layouts\main.hbs'
error_screen
structure_screen
Express-Handlerbars (the view engine you're using) expects a main layout file which you can see on the docs (search for "main.handlebars") https://github.com/ericf/express-handlebars
You can also see the directory structure express handlebars expects under https://github.com/ericf/express-handlebars#basic-usage
This acts as a "main" layout that your other views extend. So you can put common code in main such as a navbar etc.
You can either follow the docs or when you render your views use {layout:false} as one of the props passed in e.g
res.render('home', {layout: false});
and see if that works. You can also read about the defaultLayout here https://github.com/ericf/express-handlebars#defaultlayout
You could potentially try setting the default layout to false by default, though I don't know what effect this will have or if there are other unintended consequences. It might not even work at all.
app.engine('hbs', exphbs({extname: '.hbs', defaultLayout:false}));
Your best bet is to use a main layout, so you can put the common code in there, so if you wanted to update your logo for example you would only have to do it in 1 place rather than every view.
To do this, in your "views" directory create another directory called "layouts" and add a file called "main.hbs" with the following code in it. The {{{body}}} area is where your code from other views will be rendered.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example App</title>
</head>
<body>
{{{body}}}
</body>
</html>

Multer returning req.file undefined

I know this question has been asked plenty of times before, and I've tried implementing those solutions, but they don't really work for me.
I have been tearing my hair out trying to figure out how to upload a file and read the file size through Node. I initially tried using the formidable npm, which seems to no longer be maintained as I can't find documentation on it. I had no way of dealing with the errors so I tried using multer. However, I repeatedly get an undefined log when I try to log req.file.
I have the server.js code below
var express = require('express');
var formidable = require('formidable');
var multer = require('multer');
var path = require('path');
var upload = multer({dest: './uploads'});
var fs = require('fs');
var app = express();
var PORT = 8080;
app.use(express.static(__dirname+'/views'));
app.set('views', './views');
app.set('view engine', 'jade');
app.get('/', function(req, res){
res.render('index.jade');
});
app.post('/upload', upload.single('Upload'),function(req, res){
console.log(req.file);
});
app.listen(PORT, function(){
console.log('Express listening on port: '+PORT);
});
My javascript code with the AJAX call is provided below
$('#upload-butt').on('change', function(){
var file = $(this).get(0).files;
console.log(typeof file);
if(file.length > 0){
var formData = new FormData();
formData.append('Upload', file, file.name);
$.ajax({
url: '/upload',
type: 'POST',
data:formData,
processData:false,
contentType:false,
error: function(jXhr, status){
console.log('error: '+status);
},
success: function(data){
console.log('upload successful: '+data);
}
})
}
});
My index.jade code is given below
html
head
link(rel='stylesheet', href='style.css', type='text/css')
title Upload file for shortening
body
h1 Welcome to file metadata service
div(id='upload-button')
form(enctype='multipart/form-data', method='post', action='/upload')
input(name='Upload', type='file', id='upload-butt')
div(id="submit-button")
form(action = '/submit')
button(type="submit", value='Submit', id='submit-butt') Submit
script(src="https://code.jquery.com/jquery-2.2.0.min.js")
script(src="upload.js")
I am ready to tear my hair out, so I will be very grateful to anyone who can help me here! Thanks!
You have not applied middle correctly.
You can use something like this:
var express = require('express')
var multer = require('multer')
var app = express()
app.use(multer({ dest: './uploads/'}))
You can access the fields and files in the request object:
console.log(req.body)
console.log(req.files)
So similarly in ur code you have to apply
var express = require('express');
var formidable = require('formidable');
var multer = require('multer');
var path = require('path');
var upload = multer({dest: './uploads'});
var fs = require('fs');
var app = express();
var PORT = 8080;
app.use(upload);
app.use(express.static(__dirname+'/views'));
app.set('views', './views');
app.set('view engine', 'jade');
app.get('/', function(req, res){
res.render('index.jade');
});
app.post('/upload', upload.single('Upload'),function(req, res){
console.log(req.file);
});
app.listen(PORT, function(){
console.log('Express listening on port: '+PORT);
});
You're submitting a different <form> than the one with the image, the correct way is to place all content in a single <form>. This way you're submitting the form which includes the file.
html
head
link(rel='stylesheet', href='style.css', type='text/css')
title Upload file for shortening
body
h1 Welcome to file metadata service
div(id='upload-button')
form(enctype='multipart/form-data', method='post', action='/upload')
input(name='Upload', type='file', id='upload-butt')
button(type="submit", value='Submit', id='submit-butt') Submit
script(src="https://code.jquery.com/jquery-2.2.0.min.js")
script(src="upload.js")
This should work, for the jade part.
(docs about multer)

Node.js public css files 404 not found

I'm learning node.js and I have an error serving public CSS files to one URL.
It works with almost every pages, I go on the page and the css file is loaded from 127.0.0.1/css/style.css.
When the URL is 127.0.0.1/project/idProject it tries to get the css file from 127.0.0.1/project/css/style.css.
// INCLUDE MODULES =======================================================
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var Twig = require('twig');
var twig = Twig.twig;
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var configDB = require('./config/database.js');
// Assets ================================================================
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.favicon(path.join(__dirname, 'public/images/favicon.ico')));
// Start mongoose
mongoose.connect(configDB.url);
// USER MANAGEMENT =======================================================
require('./config/passport')(passport); // pass passport for configuration
app.use(express.logger('dev')); // log every request to the console
app.use(express.cookieParser()); // read cookies (needed for auth)
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies
app.set('view engine', 'twig'); // set up twig for templating
app.use(express.session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash())
// ROUTES =======================================================
// Set authentication variable
app.use(function (req, res, next) {
app.locals.login = req.isAuthenticated();
next();
});
require('./app/routes.js')(app, passport);
//ERROR MANAGEMENT =======================================================
app.use(app.router);
app.use(function(req, res, next){
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.render('errors/404.twig', { url: req.url });
return;
}
// respond with json
if (req.accepts('json')) {
res.send({ error: 'Not found' });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
});
/*app.use(function(err, req, res, next){
// we may use properties of the error object
// here and next(err) appropriately, or if
// we possibly recovered from the error, simply next().
res.status(err.status || 500);
res.render('errors/500.twig', { error: err });
});*/
//SOCKET IO =======================================================
//Quand on client se connecte, on le note dans la console
io.sockets.on('connection', function (socket) {
console.log("New connection");
});
// LISTEN SERVER =======================================================
server.listen(80);
Any idea on how to solve this ?
Regards !
I tried approach which I saw in the comments, and because it did not work for me, I am posting an answer that worked.
All .css files are static, so you have to serve them to the client. However, you do not serve static files as a express middleware. Therefor you have to add them.
app.use(express.static(__dirname, 'css'));
Hi it was a problem for me to solve this, but with the help of salvador it was posible.
The only thing that im going to put is all the code and the you make the reference in the html, you only need to put the file not the folder in the html file.
//The index.js code
var express = require('express');
const path = require ('path');
//app va a ser mi servidor.
var app = express();
app.set('port', 3000)
//app.use(express.static('./public'));
//app.use(express.static( 'css'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'css')));
app.listen(app.get('port'), () => {
console.log('localhost:3000')
} );
this is the structure

where to define database logic in express?

I am using express node js for my redirection project.I am just beginner in express node js.
I don't know where to define my database logic.
Aim:- Getting the url from database and redirect to that url.
my directory structure:-
app.js
controller
---------index.js
node_modules
package.json
public
------images
------stylesheet
------javascripts
routes
-----index.js
views
app.js
var express = require('express')
, http = require('http')
, mysql = require('mysql')
, path = require('path');
var app = express();
var controller = require('./controller')({app: app});
// all environments
app.configure(function() {
app.set('port', process.env.PORT || 8888);
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(app.router);
app.get('/', function( req, res) {
res.render('index');
});
});
//connect to mysql database
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'xxxxx',
database : 'nodejsmysql'
});
connection.connect();
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
controller
function controller(param)
{
var app = param.app;
app.get('/id', function(request, response) {
var id= request.param("id");
// i need to use this id to fetch corresponding url from database and redirect that url.
});
}
module.exports = controller;
database query:- select url from db where id='id';
Typically you create Models to handle database logic. The general pattern is
app.js - list all your routes
routesX.js - handles code for routes (say /x/whatever). This is where you evaluate HTTP values like querystring, cookies, and form data. Renders the view after calling the model.
modelsX.js - handles the domain logic for the routes (including database access)
So for example in a routesX.js you might have something like this:
var blogModel = require('./modelsX.js');
exports.blogAll = function(req, res) {
blogModel.getAll(function(data) {
res.render('someView', data);
});
}
and in your modelsX.js you might have something like this:
exports.getAll = function(callback) {
// get data from the database here
// and call the callback
callback()
}
If you want to see a full end-to-end example, check out this repo: https://github.com/hectorcorrea/hectorcorrea.com/blob/master/routes/blogRoutes.js

Using express to set up a basic server

I have a node.js application and I am stuck getting an error message when I try to load the homepage. I will do my best at laying out my architecture below. It goes index.js --> server.js --> router.js --> requestHandlers.js
I am using a combination of express (www.expressjs.com) and nodebeginner.org. Sorry for the long question.. just wanted to get as much information down as possible.
index.js (creates handle object that contains pathname/requesthandler information, calls function to start server) I start with router.route here and pass it along each step
var server = require("./server");
var router = require('./router');
var requestHandlers = require('./requestHandlers');
// Routes
var handle = {}
handle['/'] = requestHandlers.home;
server.start(router.route, handle)
server.js (starts the server, THIS IS WHERE I WANT TO CONFIGURE THE SERVER, gets a the pathname from the URL, and passes it on to the route module)
var http = require("http");
var url = require('url');
var express = require('express');
function start (route, handle) {
var onRequest = function(request, res) {
var pathname = url.parse(request.url).pathname;
console.log("request for " + pathname + " recieved.");
route(handle, pathname, res);
}
var app = express.createServer(onRequest).listen(8888);
if (app.configure) {
console.log('app exists'); //logging correctly
}
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); //logs correct with 8888 and development
}
exports.start = start;
router.js (the function route passed from index --> server which calls the route function in router.js, calls the requestHandler that matches the pathname in handle object)
function route (handle, pathname, res) {
console.log("About to route a request for" + pathname); //About to route a request for/stylesheets/style.css SEE BELOW******* this is the error
if (typeof handle[pathname] === 'function') {
handle[pathname] (res);
}
else {
console.log('no request handler found for' + pathname);
}
}
exports.route = route;
requestHandler.js (interacts with the res/req objects, functions are mapped to certain pathnames, only called when those pathnames are requested thanks to the router)
var home = function(res){
res.render('index', { title: 'WWYB?' });
console.log('homepage rendered'); //correctly logs for pathname = '/'
//click();
};
exports.home = home;
***when i go to request localhost:8888 it tries to make a bunch of requests. first it requests "/" correctly but then keeps going through logging everything saying "About to route a request for/stylesheets/style.css" Eventually the page loads with no css. The pathname as indicated in my layout.jade file is exactly that '/stylesheets/style.css'.
Why is the pathname ever evaluating to /stylesheets/style.css? I think node is doing something in the background and I dont fully understand it.
Let me know if you need more info. Thanks!
Like #TJHolowaychuk commented you really should check the manual, and follow a bunch of tutorials. Anyway, I'll try to help you a bit.
The is a very basic explanation. Express allows you to use sub applications, so you can have different part of you application in different files. It has it's own router too. If you need to do something with the request and/or the response before the route is processed, you can create a middleware. If you want you configurations in a different module, then return a function in it.
So an example of server.js :
var $express = require('express'),
app = module.exports = $express.createServer(),
subapp = require('./subapp'),
configure = require('./configure');
// Each of our own configure returns a function that will be
// called by app.configure
app.configure(configure.all(app));
app.configure('development', configure.devel(app));
app.configure('production', configure.prod(app));
// Use our sub application
app.use(subapp);
// Now listen
app.listen(3030)
subapp.js :
var $express = require('express'),
subapp = module.exports = $express.createServer();
// Add a handler for GET / to our sub-application
subapp.get('/', function (req, res) {
res.end('Hello world!');
});
Finally configure.js :
var $express = require('express');
exports.all = function (app) {
return function () {
// Global configurations
app.use($express.bodyParser());
app.use($express.methodOverride());
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use($express.static(__dirname + '/public'));
//...
// If you want to do something with/on the request/response
// you can create a middleware
app.use(function (req, res, next) {
console.log('caught request %s %s', req.method, req.path);
// Don't forget the callback
next();
});
};
};
exports.devel = function (app) {
return function () {
// Development configurations
};
};
//...
Go to localhost:3030 with your favorite browser, it displays "Hello world!", this is our request handler. If you look at the terminal, you'll see "caught request GET /", this is our middleware.
Your stylesheets, client-side javascripts, etc. should be in /public. app.use(express.static(__dirname + '/public')) will serve these.
Let's say you have /public/stylesheets/all.css, then in your jade template you can include it like this link(rel='stylesheet', href='/public/stylesheets/all.css')
Now, you'll have to experiment and learn more about node and express before even thinking to deploy something to production, these websites may help you:
howtonode
nodetuts
Hope this tiny-micro-tut helps you.
woah this is pretty confusing, you might want to start with the app express(1) can generate for you

Categories

Resources