I can't open the route "/d" but "/" is working. What could be the problem? I tried different things but id did not find a solution.
var myApp = angular.module('myApp',['ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider.when('/', {
controller: 'OrdersController',
templateUrl: 'views/lp.html'
})
.when('/d',{
controller:'OrdersController',
templateUrl: 'views/order_detail.html'
})
.otherwise({
redirectTo: '/'
});
});
Server side code looks like this. Maybe they don't like each other ;)
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
app.use(express.static(__dirname+'/client'));
app.use(bodyParser.json());
Order = require('./models/order.js');
//Connect to Mongoose
mongoose.connect('mongodb://localhost/groundlevel');
var db = mongoose.connection;
app.get('/', function(req, res){
res.send('Please use /api/order');
});
app.get('/api/orders', function (req, res) {
Order.getOrders(function (err, orders) {
if(err){
throw err;
}
res.json(orders);
})
});
app.get('/api/orders/:_id',function (req, res) {
Order.getOrderById(req.params._id, function (err, order) {
if(err){
throw err;
}
res.json(order);
})
});
app.post('/api/orders', function (req, res) {
var order = req.body;
Order.addOrder(order, function (err, order) {
if(err){
throw err;
}
res.json(order);
})
});
app.listen(3000);
console.log('Running on Port 3000...');
To let your client side application handle the routing. In your server side do the following
var path= require('path');
// All other routes should redirect to the index.html
app.route('/*')
.get((req, res) => {
res.sendFile(path.resolve(__dirname + '/client/index.html'));
});
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;
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 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 '/'
I'm using NodeJS, ANgularJS, and MongoDB with mongoose to make a website. I'm having some trouble adding an object in mongoDB. The name of the object is Todo.
Here are the models of Todo:
var mongoose = require('mongoose');
var TodoSchema = new mongoose.Schema({
name: String,
password : String,
completed: Boolean,
note: String
});
module.exports = mongoose.model('Todo', TodoSchema);
In the controller I create a new Todo and push it
angular.module('app').controller('Connexion', ['$scope', 'Todos','$location', function($scope,Todos, $location) {
$scope.editing = [];
$scope.todos = Todos.query();
$scope.save = function() {
var todo = new Todos({ name: "test", password: "test", completed: false });
$scope.todos.push(todo);
Todos.save($scope.todo);
}
}]);
This is my html page, each time I click on the button I Have a new todo created and it's displayed on screen:
<button ng-click="save()">Creer POST </button>
<ul>
<li ng-repeat="todo in todos">
{{todo.name}}
{{todo.password}}
</li>
</ul>
But I have a problem, the new object is not added on the database. How can I do it?
This is my files in the back-end :
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Todo = require('../models/Todo.js');
/* GET /todos listing. */
router.get('/', function(req, res, next) {
Todo.find(function (err, todos) {
if (err) return next(err);
res.json(todos);
});
});
/* POST /todos */
router.post('/', function(req, res, next) {
Todo.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /todos/id */
router.get('/:id', function(req, res, next) {
Todo.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* PUT /todos/:id */
router.put('/:id', function(req, res, next) {
Todo.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* DELETE /todos/:id */
router.delete('/:id', function(req, res, next) {
Todo.findByIdAndRemove(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
And if this can help this the back-end file 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 mongo = require('mongodb');
var Post = require('./models/Post.js');
var routes = require('./routes/index');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/todoApp', function(err) {
if(err) {
console.log('connection error', err);
} else {
console.log('connection successful');
}
});
var app = express();
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('/', function(req, res, next){
res.sendFile(__dirname + '/public/index.html');
});
var found = ['DB Connection not yet established. Try again later. Check the console output for error messages if this persists.'];
module.exports = app;
$scope.todo from Todos.save($scope.todo); is not defined so this is why you might not manage to save anything
I'm having trouble getting my head around $resource. I'm trying to apply a delete method to remove a MongoDB database entry when user presses a delete button. I am using Angular 1.4 with Express and Mongoose.
Here is my HTML:
<body ng-app="polls" ng-controller="PollsCtrl">
Polls:
<ul>
<li ng-repeat="question in questions">
{{ question.questionName }}
<button ng-click="deletePoll(question._id, $index)">Delete</button>
</li>
</ul>
...
Here's the client-side controller:
"use strict";
var app = angular.module('polls', ['ngResource']);
app.controller('PollsCtrl', function ($scope, $resource) {
var Poll = $resource('/api/polls');
var PollID = $resource('/api/polls/:pollID');
Poll.query(function (results) {
$scope.questions = results;
});
$scope.questions = [];
$scope.questionName = '';
$scope.addPoll = function () {
var poll = new Poll();
poll.questionName = $scope.questionName;
poll.$save(function (result) {
$scope.questions.push(result);
$scope.questionName = '';
});
};
$scope.deletePoll = function (id, index) {
var poll = new PollID();
poll.$remove(function () {
$scope.questions.splice(index, 1);
});
};
});
here's the server file including the remove method:
var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
mongoose.connect('mongodb://localhost/poll-app');
app.use('/controllers', express.static(__dirname + '/controllers'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/polls', function (req, res) {
res.sendFile(path.join(__dirname + '/polls.html'));
});
app.get('/add-poll', function (req, res) {
res.sendFile(path.join(__dirname + '/add-poll.html'));
});
var pollSchema = new mongoose.Schema({questionName: String});
var Poll = mongoose.model('Poll', pollSchema);
var creater = function (req, res) {
var poll = new Poll(req.body);
poll.save(function (err, result) {
if (err) throw err;
res.json(result);
})
};
var list = function (req, res) {
Poll.find({}, function (err, result) {
if (err) throw err;
res.json(result);
});
};
var remove = function (req, res) {
console.log(req.params);
var poll = new Poll(req.body);
poll.remove({_id: req.params}, function (err, result) {
if (err) throw err;
res.json(result);
});
};
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.post('/api/polls', creater);
app.get('/api/polls', list);
app.delete('/api/polls/:pollID', remove);
app.listen(3000, function () {
console.log('HI');
});
I'm pretty sure the error lies in the server's remove() method. When i test this, i actually get:
DELETE http://localhost:3000/api/polls 404 (Not Found)
as though it isn't routing to where i want it to.
poll.$remove({pollID:id}, function () {
$scope.questions.splice(index, 1);
})
in your case, I think it's better to use $http:
$http.delete('/api/polls/pollID/'+req.params).
This way, you don't have to get the object before delete