Cannot GET /about page in MEAN application - angularjs

I want to integrate angular routing into my node app, but I'm getting an error and not sure how to resolve it. I just want to have a link to redirects to an about.html file, that is inside a directory called public.
In my index.html file I have a link:
About
In my server.js I have this:
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('contactlist', ['contactlist']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.set('port', process.env.PORT || 3000);
In my js file I have the $routeProvider set up as follows:
myApp.config(function($routeProvider){
$routeProvider
.when('/about',{
templateUrl: '/about.html'
});
});

Related

AngularJs $resource.save returning 404 error

I am getting a 404 error while trying to create a new JSON file locally.
Here is my service:
eventsApp.factory('eventData', function($resource){
var resource = $resource('/data/event/:id', {id:'#id'});
return {
getEvent: function() {
//return $http({method: 'GET', url:'/data/event/1'});
//return $resource('/data/event/:id', {id:'#id'}).get({id:1});
return resource.get({id:1});
},
save: function(event) {
event.id = 999;
return resource.save(event);
}
}
});
The web.server js code is as below:
var express = require('express');
var path = require('path');
var events = require('./eventsController');
var bodyParser = require('body-parser');
var app = express();
var rootPath = path.normalize(__dirname + '/../');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(express.static(rootPath + '/app'));
app.get('/data/event/:id', events.get);
app.post('/data/event:id', events.save);
app.listen(8000);
console.log('Listening on port 8000...');
The get function works perfectly fine, but the post always throws a 404 error.
See a screenshot below:
What am I missing?
As said in comments, your Express server routes are bad defined.
So when trying to POST data on /data/event/999, no route is defined for.
app.get('/data/event/:id', events.get);
app.post('/data/event/:id', events.save); // You forgot '/' here

When use body-parser module in my app , get GET ERR_EMPTY_RESPONSE

I have this Error when I'm trying to load my website
GET http://localhost:3000/ net::ERR_EMPTY_RESPONSE
I'm using Mean Stack Technologies,
When I remove app.use(bodyParser.json); from my code the page load very well
the code of my server.js file :
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
var authenticationController = require('./server/controllers/authentication-controller');
mongoose.connect('mongodb://localhost:27017/time-waste');
app.use(bodyParser.json);
app.use('/app',express.static(__dirname + '/app'));
app.use('/node_modules',express.static(__dirname + '/node_modules'));
app.get('/',function(req,res){
res.sendfile('./index.html');
});
//Authentication
app.post('/api/user/signup',authenticationController.signup);
app.listen('3000',function(){
console.log("listening on port 3000");
});
the auth controller file
var mongoose = require('mongoose');
var User = require('../datasets/users');
module.exports.signup = function(req,res){
console.log(req.body);
var user = new User(req.body);
user.save();
res.json(req.body);
};
the angular controller
angular.module('TimeWaste').controller('signUpController',['$scope','$state','$http',function($scope,$state,$http){
$scope.createUser = function(){
console.log($scope.newUser);
$http.post('api/user/signup',$scope.newUser).success(function(response){
}).error(function(error){
console.log(error);
});
};
}]);

Express JS 4 and html5Mode redirect not working

I'm trying to implement html5mode(true) for my angular app on my Node/Express server.
I'm getting the dreaded "cannot /GET" error when I try to reload.
The fix that I see being implemented for this on the server is by adding a catch all get request in the express app.js.
I've done that, but It's not working for me.
Here is my code where I add the catch all at the bottom, but when I reload, I get the following message: Error: "ENOENT: no such file or directory, stat '/Users/christophernakea/Documents/Projects/express4/testproj/server/client/app/index.html' at Error (native)"
That's clearly not what I'm calling below.
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 cors = require('cors');
mongoose.connect('mongodb://localhost/test');
var app = express();
// 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());
app.use(cors());
app.use('/api', require('./routes/api'));
app.use('/sendmail', require('./routes/sendmail'));
app.use(express.static(path.join(__dirname, '../client/app/custom')));
app.use(express.static(path.join(__dirname, '/dist')));
// 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: {}
});
});
app.all('/*', function(req, res){
res.sendFile(__dirname + '/dist/index.html');
});
module.exports = app;
My angular module has the standard...
'use strict';
angular
.module('clientApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ui.router',
'ngSanitize',
'ngTouch',
'xeditable'
])
.config(['$urlRouterProvider', '$stateProvider', '$locationProvider', function($urlRouterProvider, $stateProvider, $locationProvider) {
$urlRouterProvider.otherwise("/");
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/main.html',
controller: 'MainController'
});
}])

Page change not getting reflected in angularjs while using routeProvider

I am making an angularjs app,in which i am using Express as backend.The problem i'm facing is not being able to switch between my Html pages.Kindly help,i have tried a lot of tutorials but none of them worked.I guess there must be some problem in the path i am providing.
Here is my server.js
`
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var ejs = require('ejs');
var urlencodedParser = bodyParser.urlencoded({extended:false});
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'test'
});
connection.connect();
app.use(express.static('public'));
//app.set('views', __dirname + 'views');//this is used because res.render('../template/goto_page_options.html', {values : city});
//was not able to render the view
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.get('/', function(req, res) {
var path = require('path');
res.sendFile(path.resolve('../template/login.html'));
console.log("WOW");
})
app.get('/home', function(req, res) {
var path = require('path');
res.sendFile(path.resolve('../template/home.html'));
console.log("home requested");
})
`
This is my app.js
app.config(['$routeProvider', function ($routeProvider){
$routeProvider
.when('/',{
redirectTo: '/login'
})
.when('/home',{
templateUrl:'home.html'
})
.when('/employee',{
templateUrl:'employee.html'
})
.when('/login',{
templateUrl:'login.html'
})
.otherwise({ redirectTo: '/login' });
}]);
This is my index.html
<body ng-app="starter">
<div ng-view></div>
<script src="http://localhost/try/www/js/app.js"></script>
<script src="http://localhost/try/www/js/server.js"></script>
</body>
my directory structure is
templates
--login.html
--home.hml
js
--app.js
index.html
In your index.html, you have included
<script src="http://localhost/try/www/js/server.js"></script>
But in your directory structure, there is no such file.Check the console in your browser. There will be file not found error.
Also there is no such file
employee.html
login.html

spa with angular and express - cannot load templates

I try to create a SPA with angular on a node/express server. Please bear with me, I am confused. View engine is ejs. On my app.js I have
var routes = require('./routes/index');
app.use('/', routes.list);
index.js contains
exports.list = function(req, res){
res.render('index', {
title: 'Home'
});
};
so it can render index.ejs that contains
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="./public/javascripts/angular.min.js"></script>
<script src="./public/javascripts/angular-route.min.js"></script>
<script>
var app = angular.module('app', ['ngRoute']);
app.config(function ($routeProvider) {
// configure the routes
$routeProvider
.when('/', {
// route for the home page
templateUrl: './views/home.ejs',
controller: 'homeController'
})
.when(' /about', {
// route for the about page
templateUrl: './views/about.ejs',
controller: 'aboutController'
})
)}
app.controller('homeController', function ($scope) {
$scope.message = 'Welcome to my home page!';
});
app.controller('aboutController', function ($scope) {
$scope.message = 'Find out more about me.';
});
</script>
<title><%= title %></title>
<div ng-view></div>
<li>Home</li>
<li>About</li>
home.ejs and about.ejs are like
<h1>About Page</h1>
<p>{{ message }}</p>
1- I cannot load the angular.min.js and angular-route.min.js. I get angular is not defined for the var app = angular.module('app', ['ngRoute']); line in index.ejs file and Unexpected token < for <!DOCTYPE html> on the same file.
2- home.ejs and about.ejs dont load
3- I replace with app.use('/#', routes.list); on app.js and <a href="#"> <a href="#about"> on the index.ejs and I get error 404. Why the # character on the URL causes problems?
4- Should I also create routes for about like var about = require('./routes/about'); and app.use('/about', about.list);? Or is an SPA, so routes are not necessary because they will cause page loads?
Sorry for the big question.
Thanks in advance
UPDATE
on the index.ejs file I changed the app to sp , so no conflicts occur, but the same problems remain.
UPDATE 2
the whole app.js is
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes.list);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(4800);
module.exports = app;

Resources