I am using Angular with express. I am having problem when I try to refresh page which is not main '/', like register page http://localhost:3000/registerit gives me 404 error page not found.
Then I added this code to my server.js (express file)
app.all('/*', function(req, res) {
res.sendfile('public/index.html');
});
but It i snow always redirecting to root url. I want when I refresh page to refresh me the page I am on and to give me the same page again.
My server.js file is
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var passport = require('passport');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
//connect to mongodb
require('./models/user.js');
require('./models/item.js');
mongoose.connect("mongodb://localhost:27017/web-shop");
var index = require('./routes/index');
var api = require('./routes/api');
var authenticate = require('./routes/authenticate')(passport);
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(session({
secret: 'super duper secret'
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());
//Initialize Passport
var initPassport = require('./passport-init');
initPassport(passport);
app.use('/', index);
app.use('/api', api);
app.use('/auth', authenticate);
app.all('/*', function(req, res) {
res.sendfile('public/index.html');
});
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
And thi is my angular routing
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'main.html',
controller: 'itemController'
})
.when('/login', {
templateUrl: 'login.html',
controller: 'authController'
})
.when('/register', {
templateUrl: 'register.html',
controller: 'authController'
})
.when('/add_item', {
templateUrl: 'dashboard.html',
controller: 'itemController'
})
$locationProvider.html5Mode(true);
})
app.all('/*', function(req, res) {
res.sendfile('public/index.html');
});
Remove app.use('/', index); and it should work fine as it does not allow above route to send index.html every time it encounters route other than and including '/'
Related
I have developed web app using angularjs single page application.Now I am building my own web server using nodejs.
The index page is visible when page is loaded but on navigation to other pages.
The get request goes on infinite loop with 304 status.
**Please note I need css and javascript for bootstrap and jquery.**When these are loaded I receive the error.I have inserted app.js(server config),index.js(nodejs routing config),moduleapp.js(angularjs routing config) and picture of error.
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/home", {
templateUrl : "/views/home.hbs",
controller : "homeCtrl"
})
.when("/aboutme",{
templateUrl:"/views/aboutme.hbs",
controller:"aboutCtrl"
})
.when("/education", {
templateUrl : "/views/education.hbs",
controller : "eduCtrl"
})
.when("/interest",{
templateUrl:"/views/interest.hbs",
controller:"interestCtrl"
})
.when("/gallery",{
templateUrl:"/views/gallery.hbs",
controller:"galleryCtrl"
})
.when("/contact", {
templateUrl : "/views/contact.hbs",
controller : "contactCtrl"
});
});
app.controller("homeCtrl", function ($scope) {
$scope.msg = "Welcome to homepage";
});
app.controller("aboutCtrl", function ($scope) {
$scope.msg = "About me";
});
app.controller("eduCtrl", function ($scope) {
$scope.msg = "Hi Academics";
});
app.controller("interestCtrl", function ($scope) {
$scope.msg = "My interests";
});
app.controller("galleryCtrl",function($scope){
$scope.msg="My photos";
})
app.controller("contactCtrl", function ($scope) {
$scope.msg = "Contact me";
});
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('layout');
});
router.get('/:name', function(req, res, next) {
var name=req.params.name;
res.render(name);
});
module.exports = router;
<!-- end snippet -->
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 hbs=require('express-handlebars');
var index = require('./routes/index');
var app = express();
// view engine setup
app.engine('hbs',hbs({extname:'hbs'}))
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
// 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);
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;
this is my code I am running the server but I can't get the page index.html
the error is
app.get('/',function(request,response){
console.log("/");
response.sendFile(__dirname+"/views/index.html");
})
The error is
This 127.0.0.1 page can’t be found
No webpage was found for the web address: http://127.0.0.1:5000/home
HTTP ERROR 404
I dont think the server is getting the get request. I don't see the console.log() getting called.
The entire code:
var http = require("http");
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 routes = require('./routes/index');
var users = require('./routes/users');
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.use(express.static(__dirname+"/"));
app.use('/', routes);
app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
app.get('/',function(request,response){
console.log("/");
res.sendfile('views/index.html', {root: __dirname });
});
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
// http.createServer(function (request, response) {
// // Send the HTTP header
// // HTTP Status: 200 : OK
// // Content Type: text/plain
// response.end('Hello World\n');
// response.writeHead(200, {'Content-Type': 'text/plain'});
// // Send the response body as "Hello World"
// }).listen(8081);
app.listen(5000);
// Console will print the message
console.log('Server running at http://127.0.0.1:5000/');
module.exports =app;
In your error, http://127.0.0.1:5000/home is not found that mean you did not define /home route. So you need to update app.get('/') route as following
app.get('/home?',function(request,response){
console.log("Url: " + request.url);
response.sendfile('views/index.html', {root: __dirname });
});
Try this
app.use('/', routes);
app.use('/users', users);
//add your route to get file
app.get('/',function(request,response){
console.log("/");
response.sendfile('views/index.html', {root: __dirname });
});
See the doc understand it correctly res.sendFile
Hit this URL http://127.0.0.1:5000/ to get your file in browser
I am new in MEAN technology and Developing Web APP. I established the
Connection and login successfully. I want to establish the session after login
But I don't know how to established the session in MEAN app.
Connection established using 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 routes = require('./routes/index');
var api = require('./routes/api');
var users = require('./routes/users');
// database connectivity
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/ditroapp');
var db = mongoose.connection;
db.on('error', function (err) {
console.log('mongo connection error', err);
});
db.once('open', function () {
console.log('mongo connected.');
});
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(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/api', api);
app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
and here is code in controller.js using this I login successful.
$scope.loginpage = function(){
$http({
method: 'POST',
url: '/api/login',
data: {email:$scope.email, password:$scope.password}
}).then(function successCallback(response) {
if(response.data.error)
{
alert("Invalid email pasword");
}
else
{
$scope.dp = response.data;
$localStorage.pp = $scope.dp;
//console.log($localStorage.pp)
$location.path('/addseat');
}
}, function errorCallback(response) {
alert("Invalid email pasword");
});
}
I'm starting learning Express and Angularjs. In the project, I want to render HTML at the server side and bind data via Angularjs but it didnt work. I saw that ng-repeat is disable in browser
<body ng-app="photoApp" class="ng-scope">
<h1>Express</h1>
<p>Welcome to Express</p>
<!-- ngView: -->
<div ng-view="" class="ng-scope">
<div id="photos" class="ng-scope">
<!-- ngRepeat: photo in vm.photos -->
</div>
</div>
</body>
, therefore no data is showed. Please help me to fix that, thanks in advanced!
Project Structure
photo
--public
----javascript
------lib
------photoApp.js
--routes
----index.js
----photo.js
--views
----partials
------photo-list.pug
----error.pug
----index.pug
----layout.pug
--app.js
Server-side 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 routes = require('./routes/index');
var users = require('./routes/users');
var photos = require('./routes/photos');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// 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('/', routes);
app.use('/users', users);
app.use('/photos', photos);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/partials/:name', function(req, res, next){
var name = req.params.name;
res.render('partials/' + name);
});
module.exports = router;
photos.js
var express = require('express');
var router = express.Router();
var photos = [];
photos.push({
name: 'Node.js Logo',
path: 'http://nodejs.org/images/logos/nodejs-green.png'
});
photos.push({
name: 'Ryan Speaking',
path: 'http://nodejs.org/images/ryan-speaker.jpg'
});
router.get('/api/get-all', function(req, res) {
res.json(photos);
});
router.get('/', function(req, res) {
res.render('photos');
});
module.exports = router;
layout.pug
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
script(src='javascripts/lib/angular.js')
script(src='javascripts/lib/angular-route.js')
script(src='javascripts/photoApp.js')
body(ng-app="photoApp")
block content
index.pug
extends layout
block content
h1= title
p Welcome to #{title}
div(ng-view)
photo-list.pug
#photos
.photos(ng-repeat="photo in vm.photos")
h2 {{photo.name}}
img(src="{{photo.path}}")
Client-side code:
photoApp.js
var photoApp = angular.module('photoApp', ['ngRoute']);
photoApp.controller('PhotoListController', PhotoListController);
photoApp.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'partials/photo-list',
controller: 'PhotoListController',
controllerAs: 'vm'
})
.otherwise({
redirectTo: '/'
});
}]);
function PhotoListController($scope, $http) {
var vm = this;
vm.getAllPhotos = getAllPhotos;
function getAllPhotos(){
$http.get('/photos/api/get-all')
.success(function(response) { vm.photos = response.photos; })
.error(function() { console.log('Error when getting all photos'); });
}
}
I'm new to express and i'm trying to save some data in session and then retrieve it in another query. My client app is an AngularJS app.
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 cookieSession = require('cookie-session');
app.use(cookieParser());
app.use(cookieSession({
name: 'session',
keys: ['mySecret']
}));
app.use(bodyParser.json());
When retrieving session, it's always an empty object
{}
What can be the cause ?
Thank you !
EDIT
This my app.js now
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 cookieSession = require('cookie-session');
var methodOverride = require('method-override');
var session = require('express-session');
//Services
var routes = require('./routes/index');
var users = require('./routes/users');
var typesOperateurs = require('./routes/typesOperateurs');
var domains = require('./routes/domains');
var categories = require('./routes/categories');
var donnees = require('./routes/donnees');
var arcepData = require('./routes/arcepData');
var generalData = require('./routes/generalData');
var app = express();
var properties = require('./configs/properties');
// 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: true }));
//app.use(cookieParser('arcepSecret'));
/*app.use(cookieSession({
name: 'session',
keys: ['arcepSecret'],
httpOnly : false
}));*/
app.use(session({
secret:'arcepSecret',
resave: true,
saveUninitialized: true,
name : 'arcep.sid'
}));
app.use(bodyParser.json());
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', properties.clientHost);
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
//app.use(methodOverride);
//app.use(express.static(path.join(__dirname, 'public')));
//storing models
app.use(function(req, res, next) {
req.models = app.models;
next();
});
// Routes
app.use('/arcep', routes);
app.use('/arcep/users', users);
app.use('/arcep/typesOperateurs', typesOperateurs);
app.use('/arcep/domains', domains);
app.use('/arcep/categories', categories);
app.use('/arcep/donnees', donnees);
app.use('/arcep/arcep_data', arcepData);
app.use('/arcep/general_data', generalData);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
I'm populating the session inside
router.post('/link1', function (req, res, next) {
req.session.name = 'khalil';
});
And i'm trying to retrieve it inside
router.post('/link2', function (req, res, next) {
console.log(req.session);
})
EDIT2
I found that if invoke the services from the browser directly, everything goes fine, but when trying that from the client app wich is an angular app hosted on a tomcat server, the problem occures.
The solution is to allow credentials in the angular app.
.config(function ($routeProvider, $httpProvider) {
$httpProvider.defaults.withCredentials = true;
$http doesn't send cookie in Requests
I suggest you import the express-session (https://github.com/expressjs/session).
Try this:
var expressSession = require('express-session');
app.use(expressSession({secret:'somesecrettokenhere'}));
After to set and get the values in session:
app.get('/', function(req, res) {
req.session.hello_message = "Hello world";
res.send(req.session.hello_message);
});
The session variable hello_message will be available at everywhere in the application.
Follow full example.
1) Create file called confi.json in the same level of the app.js:
{
"SECRET": "Test",
"KEY": "test.sid",
"MAX_AGE": {
"maxAge": 3600000
}
}
2) Alter the app.js for this:
var express = require('express')
, cfg = require('./config.json')
, load = require('express-load')
, bodyParser = require('body-parser')
, compression = require('compression')
, methodOverride = require('method-override')
, expressSession = require('express-session')
, cookieParser = require('cookie-parser')
, app = express()
, cookie = cookieParser(cfg.SECRET);
app.use(compression());
app.use(cookie);
app.use(expressSession({
secret: cfg.SECRET,
name: cfg.KEY,
resave: false,
saveUninitialized: false,
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));
app.get('/', function(req, res) {
req.session.hello_message = "Hello world";
console.log(req.session.hello_message);
});
app.listen(5000, function(){
console.log("Test running");
});
module.exports = app;
3) Update the package.js:
{
"name": "test",
"version": "0.0.1",
"description": "test",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"body-parser": "~1.12.0",
"cookie-parser": "~1.3.4",
"debug": "~2.1.1",
"ejs": "~2.3.1",
"express": "~4.12.2",
"express-load": "1.1.8",
"morgan": "~1.5.1",
"serve-favicon": "~2.2.0"
}
}
4) Run npm update --save for save the dependencies.
5) Open the browser: localhost:5000 and the message should appear in the console.
As noted in the answer to a related SO question, this can occur if you're using fetch to get data from your server but you don't pass in the credentials option:
fetch('/link2', {
method: 'POST',
credentials: 'same-origin' // <- this is mandatory to deal with cookies
})
Cookies won't be passed to the server unless you include this option.