html 5 mode remove hash in angularjs+nodejs - javascript

i am new in mean stack i want to remove the hash in URL of the browser.i successfully do this but when i refresh the page at that time 'Network error 404 not found' comes so please help me to solve this problem.
below i show the code of index.html file.
<script>
var base = document.createElement('base');
base.href = 'http://localhost:3000/';
document.getElementsByTagName('head')[0].appendChild(base);
</script>
below is the code of the config.router.js
angular.module('app')
.config(
['$stateProvider', '$urlRouterProvider','$locationProvider', 'MODULE_CONFIG',
function ($stateProvider, $urlRouterProvider,$locationProvider, MODULE_CONFIG) {
$locationProvider.html5Mode(true).hashPrefix('!');
below is the code of the server.js file of the node.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 country = require('./routes/country');
var category = require('./routes/Category');
var attributes = require('./routes/Attribute');
var subscription = require('./routes/subscription');
var mall = require('./routes/mall');
var http = require('http');
var user = require('./routes/user');
var app = express();
//var cors = require('cors');
// view engine setup
//app.use(cors());
app.set('views', path.join(__dirname, '../app'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true }));
app.use(bodyParser.json({limit: '50mb'}));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(cookieParser());
//app.use(bodyParser({limit: '50mb'}));
app.use(express.static(path.join(__dirname, '../app/')));
/*allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length');
next();
};
app.use(allowCrossDomain);*/
app.use(express.static(path.join(__dirname, '../app/')));
app.use('/', routes);
app.use('/api/user', user);
app.use('/api/country', country);
app.use('/api/city', country);
app.use('/api/state', country);
app.use('/api/mall', mall);
app.use('/api/category', category);
app.use('/api/attributes', attributes);
app.use('/api/subscription', subscription);
app.set('port',3000);
mongoose.connect('mongodb://52.39.244.83 /deals');
var db = mongoose.connection;
db.on('error',erroroccured);
db.once('open',startserver);
function erroroccured(){
console.log('error');
}
function startserver(){
// mongoose.set( "debug", true );
var server = app.listen(app.get('port'), function() {
console.log('Server listening on port ' + server.address().port);
});
}
module.exports = app;
so please help me to come out from this problem thanks to all in advance.

Because you have defined the hashPrefix('!') config, your URLs will now be
index.html#!/path
If you want a plain HTML5 mode style, like
index.html/path
Just don't define the hashPrefix. It defaults to ''.
Additionally you can also get rid of the base tag, but that might create issues with are going to define a base tag, define it as
<head>
<base href="/">
</head>
Instead of localhost:3000 as this would fail on your server.

I think just use this should be fine
$locationProvider.html5Mode(true);
And in html
<head>
<base href="/">
</head>

Related

How can I serve the html, css, and js all while keeping the routes inside a module.export in a different file? Right now only html is served

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')

How can I render .ejs file from node.js controller?

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'))

Routing an Invalid Request to a 404 Error Page

I'm trying to build a server that user will be able to enter these valid paths:
localhost:9090/admin
localhost:9090/project1
and in case the user enters anything else invalid such as these the user will be redirected to root and then to the default path localhost:9090/404.html:
How do I do it?
this is my code:
app.js
var express = require('express');
var app = express();
var path = require('path');
var routes = require('c:/monex/routes/index');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('c:/monex/admin'));
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
var server = app.listen(9090, function () {
var host = server.address().address
var port = server.address().port
console.log("MonexJS listening at", port)
})
route.js
'use strict';
var express = require('express');
var app = express();
var router = express.Router();
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
/* GET home page. */
router.get('/', function(req, res) {
res.render('index');
});
router.get('/:projectname', function(req, res) {
var name = req.params.projectname;
res.render('c:/monex/myprojects/' + name +'/index');
});
app.use(function(req, res, next){
res.status(404).render('c:/monex/404.html', {title: "Sorry, page not found"});
});
module.exports = router;
Expressjs has a pretty cool way of handling errors and routing them.
1/ To Confirm if project exists
We use the filesystem module to confirm if it exists, using the access API, you can read more on the module at https://nodejs.org/dist/latest-v6.x/docs/api/fs.html
var fs = require('fs') // We'll need to ask the filesystem if it exists
var projectname = 'myfolder';
// Excerpt from your code, but Modified
router.get('/:projectname', function(req, res) {
var name = req.params.projectname;
fs.access(name, fs.constants.F_OK, function(err) {
if(!err) { // directory exists
res.render('c:/monex/myprojects/' + name + '/index');
return;
}
// Directory does not exist
next({statusCode: 404});
})
});
2/ To route the error properly
From the above code, we said anytime directory does not exist in nodejs, call next with an error object, i.e next(err), the difference between next() and next(err) is that there are two types of middlewares in expressjs, the first is:
app.use("/", function(req, res, next) {})
while the second is
app.use("/", function(err, req, res, next) {})
The difference between the two is that, the first one is a normal middleware that routes requests through. But the second is called a error handling middleware. Anytime that next function is called with an argument, express jumps to route it through error handling middlewares from there on. So, to solve your problem.
You will want to solve this at the app level so that all across all routers, you can have 404 pages delivered.
In app.js
function Error404(err, req, res, next) {
if(err.statusCode === "404") {
res.status(404).render('c:/monex/404.html', {title: "Sorry, page not found"});
}
// YOu can setup other handlers
if(err.statusCode === "504") {}
}
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(Error404);
REFERENCES
http://expressjs.com/en/guide/error-handling.html
https://www.safaribooksonline.com/blog/2014/03/12/error-handling-express-js-applications/
https://github.com/expressjs/express/blob/master/examples/error-pages/index.js
Try changing the signature of your 404 handler function
Express will use it as an error handler of just add change function parameters to: (err, req, res, next)
I also got it fixed by adding this to my app.js
app.use(function (err, req, res, next) {
res.render('c:/monex/505.html', { status: 500, url: req.url });
})
making it look like this
var express = require('express');
var app = express();
var path = require('path');
var routes = require('c:/monex/routes/index');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('c:/monex/admin'));
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(function (err, req, res, next) {
res.render('c:/monex/404.html', { status: 404, url: req.url });
})
var server = app.listen(9090, function () {
var host = server.address().address
var port = server.address().port
console.log("MonexJS listening at", port)
})

NodeJS and ExpressJS Router.use() error

I get this error:
TypeError: Router.use() requires middleware function but got a Object at Function. (C:/Users/peter/Desktop/mean/express-server/node_modules/express/lib/router/index.js:458:13)
I was testing my Api in post man and I got this error.
I got it when i in my app.js when I did app.use('/api',api);
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 session = require("express-session");
var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/jokesApi');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon(path.join(__dirname, 'public/images', '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(session({secret:'secret_3162735',saveUninitialized:true, resave: true}));
// The error comes from here
app.use('/api',api);
app.use(function (req, res, next) {
var session = req.session;
var input = req.body;
if(session.userName){
return next();
}else if(input.userName){
session.userName = input.userName;
return res.redirect('/');
}else{
req.url='/login';
return next();
}
});
app.use('/', routes);
app.use('/users', users);
module.exports = app;
JokesApi.js:
var express = require('express');
var jokes = require('../model/jokes');
var session = require("express-session")
var router = express.Router();
router.get('/joke/random',function(req,res,next){
res.end({joke: jokes.getRandomJoke()});
});
router.get('/jokes',function(req,res,next){
res.end({joke: jokes.allJokes});
});
router.post('/joke', function(req,res){
var funJoke = req.body;
var jsonJoke = funJoke.Joke;
jokes.addJoke(jsonJoke);
res.end({funnyNewJoke: jsonJoke});
})
You're not exporting your router in jokesApi.js. Add this to the end of that file:
module.exports = router;
The module jokesApi needs to be exported:
module.exports = router;
Try to follow this example: http://expressjs.com/en/guide/routing.html

Why my ejs is not rendering on redirecting?

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('/', ...);

Categories

Resources