I'm using express.js and ejs.
I will post below two codes for the app.js file. The thing is that ejs and layout.ejs do not work with the one of those two codes, but it works perfectly with the other
Here are the two codes:
The first one, which ejs is working:
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const path = require('path')
const app = express();
// Bodyparser
app.use(express.urlencoded({extended:false}));
/// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
//PUBLIC FOLDER(css and js)
app.use(express.static(path.join(__dirname,'/public')));
// Express body parser
app.use(express.urlencoded({ extended: true }));
// Routes
app.use('/', require('./routes/index.js'));
app.use('/users', require('./routes/users.js'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on port ${PORT}`));
and the second one, which ejs is not working:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 5000;
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const path = require('path')
// Bodyparser
app.use(express.urlencoded({extended:false}));
//ROUTES
app.use('/', require('./routes/index'))
app.use('/users', require('./routes/users'))
// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
app.set('view options', { layout:'layout.ejs' });
//PUBLIC FOLDER(css and js)
app.use(express.static(path.join(__dirname,'/public')));
//DB CONFIG
const db = require('./config/keys').MongoURI;
// //Connect to mongo
mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then( () => console.log('MongoDB Connected...'))
.catch( err => console.log(err));
app.listen(PORT, console.log(`Server started on PORT ${PORT}`));
I'm trying to figure out what's the issue with the second code and doesn't make the ejs work. Can anyone have a quick glimpse and compare these two and tell me what's the problem? Thank you for your time
Related
I'm trying to set up a simple express project, and backend will be purely for api and frontend will be vue. I tried adding an api router, and not only does it not work, but even the root page doesn't work. I've not coded in express for a very long time, and wondering if some one could guide me on what's the problem? The error message is 404 NotFoundError: Not Found.
I'm navigating to localhost:3000, and I can see the call on the terminal, so port should be correct too?
/src/api/urls.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('Just a test');
});
module.exports = router;
I didn't change the folder structure/naming for the original routes/index.js.
/src/routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('Just a test');
});
module.exports = router;
And for the main file
/src/app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var apiRouter = require('./api/urls');
var app = express();
app.use(require('connect-history-api-fallback')());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/api', apiRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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;
All good except endpoint url that should be with middleware function only. Modifying these should work,
/src/api/urls.js
var express = require('express');
var router = express.Router();
router.get('/api/test', function(req, res) {
res.send('Just a test');
});
module.exports = router;
/src/routes/index.js
var express = require('express');
var router = express.Router();
router.get('/api/test2', function(req, res) {
res.send('Just a test');
});
module.exports = router;
In app.js you should register your routes as,
// Routes
app.use([
require('./src/api/urls'),
require('./src/routes/index'),
]);
Access by url ( http://<yourhost>/api/test1 )
Hope Youre all are doing Great,Im new in Expressjs and doing a project in it.
Actually I m getting problem to render a file that is place inside the a folder named as index.hbs in views directory,
When I try to access a found this error :
Error: Failed to lookup view "/blogger_dasboard" in views directory "C:\Users\HBK1007\Desktop\ExpressjsFyPEPakTourisum\template\views"
Im attaching folder structure images and my code as well
Here is the codeenter image description here
`
const express = require("express")
const app = express()
const path = require('path')
const port = 8000;
const hbs =require('hbs')
const bcrypt =require("bcryptjs")
// establishing db connection
require('./db/db_connec');
// Getting the collection of DB
const Registration=require('./models/registrationdb')
const NewsletterSubsciber=require('./models/newsletter')
const ContactUs_Client =require("./models/contactus")
// this is for DB data conersions
app.use(express.json());
app.use(express.urlencoded({extended:false}))
//public static port
const static_path = path.join(__dirname, '../public')
const tempalte_path = path.join(__dirname, '../template/views')
const bloggerdashboard_path = path.join(__dirname, '../template/views/blogger_dashboard')
const partials_path =path.join(__dirname,'../template/particles')
app.set('view engine', 'hbs');
app.set('views', tempalte_path)
hbs.registerPartials(partials_path)
app.use(express.static(static_path))
// BloggerDashboard Routes
app.get('/blogger_dashboard', (req, res) => {
res.render('/blogger_dasboard')
})
app.listen(port, () => {
console.log("Listning to portss ")
})
I mirrored your project and You have few errors:
Wrong paths, too many by one dot in : static_path, tempalte_path, bloggerdashboard_path, partials_path.
Insted of res.render("/blogger_dasboard") like that: res.render("blogger_dashboard"); Without slash and you missed h letter.
Working example below without static_path bcrypt and db (for obvious reasons)..
const express = require("express");
const app = express();
const path = require("path");
const port = 8000;
const hbs = require("hbs");
// const bcrypt = require("bcryptjs");
// establishing db connection
// require("./db/db_connec");
// Getting the collection of DB
// const Registration = require("./models/registrationdb");
// const NewsletterSubsciber = require("./models/newsletter");
// const ContactUs_Client = require("./models/contactus");
// this is for DB data conersions
// app.use(express.json());
app.use(express.urlencoded({ extended: false }));
//public static port
// const static_path = path.join(__dirname, "./public");
const tempalte_path = path.join(__dirname, "./template/views");
const bloggerdashboard_path = path.join(
__dirname,
"./template/views/blogger_dashboard.hbs"
);
const partials_path = path.join(__dirname, "./template/particles");
app.set("view engine", "hbs");
app.set("views", tempalte_path);
hbs.registerPartials(partials_path);
// app.use(express.static(static_path));
// BloggerDashboard Routes
app.get("/blogger_dashboard", (req, res) => {
res.render("blogger_dashboard");
});
app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});
My Project folder and file structure:
Banging my head on this. in Express app, my get request works fine. However attempting to POST results passes an empty req.body.
here is my file tree:
index.js:
const express = require('express');
const apiRoute = require('./routes/api/index.js');
const bodyParser = require('body-parser');
// const morgan = require('morgan');
const app = express();
app.use(function(req, res, next) {
if (req.headers['content-type'] === 'application/json;') {
req.headers['content-type'] = 'application/json';
}
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/api', apiRoute);
app.listen(3000);
routes/api/index.js
const express = require('express');
const router = express.Router();
const entityRoute = require('./entity');
router.use('/entity', entityRoute);
module.exports = router;
routes/api/entity.js:
const express = require('express');
const router = express.Router();
const db = require('../../database');
router.get('/', function(req, res) {
db.select().from('entity').then(function(data) {
res.send(data);
});
});
router.post('/', function(req, res) {
console.log(req.body);
res.send(req.body);
});
module.exports = router;
Adding my Postman request in response to comment:
I have been over this numerous times, checked body-parser docs and other SO answers and can't figure this out.
following the comments, submitting json body works. screenshot below:
Not sure why this doesnt work the other way...
I've been stuck on this for a number of weeks and I can't figure it out. It's driving me crazy... Ive read numerous tutorials and it sounds like it's something that should work!
I have an expressjs server setup and a vuejs app. I want to be able to serve the vuejs routes with history browser mode and I also want to be able to setup server side routes for my api layer.
If I disable the history mode, everything works ok - but I need to enable history mode, so that I can use auth0 library and callbacks. Callbacks do not allow # in the url.
Here is my code:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const logger = require('morgan');
const history = require('connect-history-api-fallback');
const app = express();
app.use(require('connect-history-api-fallback')())
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(history({
verbose: true
}));
app.get('/api', (req, res) => res.send('Hello World!'))
app.use('/', express.static(path.join(__dirname, 'dist')));
var port = process.env.PORT || 8080;
app.listen(port);
console.log('server started '+ port);
For the code above, the vuejs app is sitting under /dist and all the routes for that one work. But when I try to hit /api - it is also being redirected to the vuejs app.
Any help would be greatly appreciated! I'm at the point where I'm thinking its just not possible.
I was having the same issue. I fixed it by adding app.use(history()) after my api routes, but before app.use('/', express.static(path.join(__dirname, 'dist')));.
So I think for you it'd be like
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const logger = require('morgan');
const history = require('connect-history-api-fallback');
const app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.get('/api', (req, res) => res.send('Hello World!'));
app.use(history({
verbose: true
}));
app.use('/', express.static(path.join(__dirname, 'dist')));
var port = process.env.PORT || 8080;
app.listen(port);
console.log('server started '+ port);
This answer helped me: https://forum.vuejs.org/t/how-to-handle-vue-routes-with-express-ones/23522/2
My app.js file looks like
let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let dotEnv = require('dotenv');
let helmet = require('helmet');
let compression = require('compression');
let passport = require('passport');
let socket_io = require("socket.io");
let app = express();
let io = socket_io();
app.io = io;
require('./server/config/socket')(io);
let useragent = require('express-useragent');
let cors = require('cors');
dotEnv.load();
require('./server/authentication/passport.local');
app.set('views', path.join(__dirname, 'server/views'));
app.set('view engine', 'jade');
app.set('view engine', 'ejs');
app.use(cors());
//app.use(logger('dev'));
app.use(helmet());
app.use(useragent.express());
app.use(compression())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(passport.initialize());
app.use(express.static(path.join(__dirname, 'public')));
/**
* Custom middle ware functions
*/
require('./server/middleware/authentication-middleware')(app);
require('./server/config/database')(app, process.env.NODE_ENV);
require('./server/routes')(app);
require('./server/middleware/custom-middleware')(app);
module.exports = app;
www file
let server = http.createServer(app);
let io = app.io;
io.attach(server);
socket.is file
module.exports = function(io) {
io.on('connection', function(socket) {
console.log('Socket.io is connected');
});
}
I have tried so many ways, but it does not fire the connection message. Does anyone here help me what is going wrong?
package.json file
expressjs : 4.16.0
socket.io : 2.0.4
Meanwhile, I have tried some other instruction, but does not work: https://onedesigncompany.com/news/express-generator-and-socket-io
Thanks in advance
In client side you can use socket.io-client
let socket = ClientSocket({ transports: ['websocket'] });
socket.on('connection',()=>{
console.log("")
})
And then at server(Considering that you have server instance.)
var socketIo = require("socket.io");
var io = socketIo.listen(server.listener);
io.on('connection', function (socketInstance) {
console.log("connected to server");
})
You might have to pass io to your routes to make it available:
require('./server/routes')(app, io);
Or use with Express Router:
const yourSpecificRoute = require('./server/youRoutes)(io);
const router = express.Router();
router.use('/route', yourSpecificRoute);