I am trying to build a simple "Hello world" Node.js/AngularJS app and am struggling. I am running the app through localhost and struggling to figure out why the HTML page isn't finding my script files.
server.js
var express = require('express');
var fs = require('fs');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/app');
app.set('view engine', 'ejs');
app.get('/', function(request, response) {
response.render('index');
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
The server is being run successfully. The angularJS application is listed below:
index.ejs
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<script src="app.js"></script>
<script src="Controllers/home.ctrl.js"></script>
</head>
<body ng-app>
<div ng-view></div>
</body>
</html>
app.js
angular.module("app", ["ngRoute"])
.config(function($routeProvider){
$routeProvider
.when("/", {
controller: "HomeController",
templateUrl: "app/Views/home.html"
});
});
home.html
home.ctrl.js
Folder structure:
Web server
index.js
app
Controllers
Views
app.js
index.ejs
The error I am getting in the console:
HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier).
GET - http://localhost:5000/app.js
HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier).
GET - http://localhost:5000/Controllers/home.ctrl.js
The problem is here:
<script src="app.js"></script>
<script src="Controllers/home.ctrl.js"></script>
<script src="app/app.js"></script>
You include two app.js, one of them has the wrong path. Maybe you meant index.js instead.
UPDATE
I see another problem here:
app.use(express.static(__dirname + '/public'));
You serve the folder public, but those files are in app
Related
I've been trying to learn angularJS, specifically 1.5 using components. My IDE is c9 so the server uses port: process.env.PORT which when I start will show the project at https://projectName-username.c9users.io (with angular-ui-router it has '/#!' on the end). This ide doesn't seem to compile es6 without using something like gulp. So I copy pasted much of the gulp code from the tutorial into my own project so that I could continue using the es6 syntax to build my own project.Everything is working pretty well except I am trying to link bootstrap 4 and my own css files from inside the project rather than a cdn and I can't seem to get the file path correct. When running the gulp file it says serving files from ./build so I tried writing the path from there but it has 404 on the resource.The closest I've come to was no errors thrown trying <link rel="stylesheet" src="#!/src/bower_components/bootstrap/dist/css/bootstrap.min.css"> but checking the network it says it's loading https://billardsWebsite-rawlejuglal.c9users.io/ with type stylesheet but nothing is actually there. Below is my file structure, the index.html file and then the gulpfile. If anyone can enlighten me on how to structure my links to find these resources I would appreciate it.
billardsWebsite
-.c9
-.git
-build
-index.html
-main.js
-node_modules
-src
-bower_components
-boostrap
-dist
-css
-bootstrap.min.css
-js
-css
-styles.css
-index.html
-.bowerrc
-.bower.json
-gulpfile.js
-package.json
-Procfile
Index.html (src/index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<title ng-bind="pageTitle"></title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="#!/src/bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<div ui-view></div>
<!-- jQuery first, then Tether, then Bootstrap JS. -->
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>
gulpfile.js
var gulp = require('gulp');
var notify = require('gulp-notify');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var babelify = require('babelify');
var ngAnnotate = require('browserify-ngannotate');
var browserSync = require('browser-sync').create();
var rename = require('gulp-rename');
var templateCache = require('gulp-angular-templatecache');
var uglify = require('gulp-uglify');
var merge = require('merge-stream');
// Where our files are located
var jsFiles = "src/js/**/*.js";
var viewFiles = "src/js/**/*.html";
var interceptErrors = function(error) {
var args = Array.prototype.slice.call(arguments);
// Send error to notification center with gulp-notify
notify.onError({
title: 'Compile Error',
message: '<%= error.message %>'
}).apply(this, args);
// Keep gulp from hanging on this task
this.emit('end');
};
gulp.task('browserify', ['views'], function() {
return browserify('./src/js/app.js')
.transform(babelify, {presets: ["es2015"]})
.transform(ngAnnotate)
.bundle()
.on('error', interceptErrors)
//Pass desired output filename to vinyl-source-stream
.pipe(source('main.js'))
// Start piping stream to tasks!
.pipe(gulp.dest('./build/'));
});
gulp.task('html', function() {
return gulp.src("src/index.html")
.on('error', interceptErrors)
.pipe(gulp.dest('./build/'));
});
gulp.task('views', function() {
return gulp.src(viewFiles)
.pipe(templateCache({
standalone: true
}))
.on('error', interceptErrors)
.pipe(rename("app.templates.js"))
.pipe(gulp.dest('./src/js/config/'));
});
// This task is used for building production ready
// minified JS/CSS files into the dist/ folder
gulp.task('build', ['html', 'browserify'], function() {
var html = gulp.src("build/index.html")
.pipe(gulp.dest('./dist/'));
var js = gulp.src("build/main.js")
.pipe(uglify())
.pipe(gulp.dest('./dist/'));
return merge(html,js);
});
gulp.task('default', ['html', 'browserify'], function() {
browserSync.init(['./build/**/**.**'], {
server: "./build",
port: process.env.PORT || '3000',
notify: false,
ui: {
port: 3001
}
});
gulp.watch("src/index.html", ['html']);
gulp.watch(viewFiles, ['views']);
gulp.watch(jsFiles, ['browserify']);
});
I created a new angular2 app using the angularCLI (just so you know my directory structure).
Running ng serve puts all my files in the dist folder and runs the hello world app in the browser with no issue.
I'm trying to run the same app in electron, but it is unable to find all the vendor files (including #angular) since it uses the file protocol in a script src:
This
<script src="vendor/es6-shim/es6-shim.js"></script>
<script src="vendor/reflect-metadata/Reflect.js"></script>
<script src="vendor/systemjs/dist/system.src.js"></script>
<script src="vendor/zone.js/dist/zone.js"></script>
produces this
file:///vendor/es6-shim/es6-shim.js Failed to load resource: net::ERR_FILE_NOT_FOUND
file:///vendor/reflect-metadata/Reflect.js Failed to load resource: net::ERR_FILE_NOT_FOUND
file:///vendor/systemjs/dist/system.src.js Failed to load resource: net::ERR_FILE_NOT_FOUND
file:///vendor/zone.js/dist/zone.js Failed to load resource: net::ERR_FILE_NOT_FOUND
How do you prepend the correct path in the file: protocol that electron uses?
My gulpfile.js:
var gulp = require('gulp'),
del = require('del'),
runSeq = require('run-sequence');
gulp.task('clean-electron', function(){
return del('dist/electron-package/**/*', {force: true});
});
gulp.task('copy:electron-manifest', function(){
return gulp.src('./package.json')
.pipe(gulp.dest('./dist/electron-package'))
});
gulp.task('copy:electron-scripts', function(){
return gulp.src('./src/electron_main.js')
.pipe(gulp.dest('./dist/electron-package'));
});
gulp.task('copy:vendor-for-electron', function() {
return gulp.src('./dist/vendor/**/*')
.pipe(gulp.dest('./dist/electron-package/vendor'))
});
gulp.task('copy:spa-for-electron', function(){
return gulp.src(["./dist/*.*", "./dist/app/**/*"])
.pipe(gulp.dest('dist/electron-package'));
});
gulp.task('electron', function(done){
return runSeq('clean-electron', ['copy:spa-for-electron', 'copy:vendor-for-electron', 'copy:electron-manifest', 'copy:electron-scripts' ], done);
});
The closest I got was doing this:
my index.html:
<script src="vendor/es6-shim/es6-shim.js"></script>
<script src="vendor/reflect-metadata/Reflect.js"></script>
<script src="vendor/systemjs/dist/system.src.js"></script>
<script src="vendor/zone.js/dist/zone.js"></script>
<script>
console.log("In my script tag:");
var systemConfigPath = 'system-config.js';
var mainPath = 'main.js';
if (window.location.protocol == "file:"){
require(__dirname + '/vendor/es6-shim/es6-shim.js');
require(__dirname + '/vendor/reflect-metadata/Reflect.js');
require(__dirname + '/vendor/systemjs/dist/system.src.js');
require(__dirname + '/vendor/zone.js/dist/zone.js');
systemConfigPath = __dirname + '/' + systemConfigPath;
mainPath = __dirname + '/' + mainPath ;
}
System.import(systemConfigPath).then(function () {
System.import(mainPath);
}).catch(console.error.bind(console));
but that still gives me issues as the vendor files reference other files inside the same directories:
Edit:
I am now trying to use webpack to build my electron app (with no success).
I also created a github repo if you would like to see the code.
From How should I configure the base href for Angular 2 when using Electron? the answer is to change you
<base href="/">
to
<base href="./">
Okay! so I am not sure it's the best answer, as it still produces some silly errors, but here we go...
My index.html now looks like this:
<body>
<electron-angular-boilerplate-app>Loading...</electron-angular-boilerplate-app>
<!--will give errors in electron... oh well-->
<script src="vendor/es6-shim/es6-shim.js"></script>
<script src="vendor/reflect-metadata/Reflect.js"></script>
<script src="vendor/systemjs/dist/system.src.js"></script>
<script src="vendor/zone.js/dist/zone.js"></script>
<script>
// if require is defined, we are on node / electron:
if (!(typeof(require) == "undefined")){
require('./vendor/es6-shim/es6-shim.js');
require("./vendor/reflect-metadata/Reflect.js");
require("./vendor/systemjs/dist/system.src.js");
require("./vendor/zone.js/dist/zone.js");
require("./system-config.js");
require("./main.js");
} else {
System.import('system-config.js').then(function () {
System.import('main');
}).catch(console.error.bind(console));
}
</script>
</body>
This allows both my angular cli application to run and my electron app to run. The <script src=... tags still produce errors in electron as it is not able to find them. I also had to remove the System.import line from electron, so hopefully that doesn't cause any issues later on.
and to run it, we just need to make sure that the app is built and run electron in the ./dist folder:
ng build && electron ./dist
Here is the branch with my working code:
https://github.com/jdell64/electronAngularBoilerplate/tree/so-37447020-answer
I am trying to set up a project using gulp and browser sync with angularjs. I cannot get browser sync to work correctly when I use the ng-view tag in my index.html file. This is the error I get in my browser console when I run browser sync:
Uncaught TypeError: Cannot read property 'data1457531805746' of null
coming from browser-sync-client.2.11.1.js:204 It works as expected, page loads fine, when ng-view/ngRoute is not used.
These are my files:
./gulpfile.js
// Spin up a server
gulp.task('browserSync', function() {
browserSync.use(spa({
selector: "[ng-app]" //Only needed for angular apps
}));
browserSync.init({
port: 8080,
server: {
baseDir: path.src
}
})
});
// Watch for changes in files
gulp.task('watch', ['browserSync'], function() {
// Watch .js files -- removed for brevity
});
// Default Task
gulp.task('default', ['watch']);
./app/controllers/controllers.js
'use strict';
/* Controllers */
var dc4SearchControllers = angular.module('dc4SearchControllers', []);
dc4SearchControllers.controller('CompanySearchCtrl', ['$scope', '$http',
function($scope, $http){
$scope.test = 'Hello, world!';
}]);
./app/index.html
<html ng-app="dc4SearchApp">
<head>
<link href="/bower_components/webui-core/dist/webui-core.min.css" rel="stylesheet">
<script src="/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/bower_components/angular/angular.min.js"></script>
<script src="/bower_components/angular-route/angular-route.min.js"> </script>
<script src="/bower_components/lodash/lodash.min.js"></script>
<script src="/bower_components/webui-core/dist/webui-core.min.js"></script>
<script src="app.js"></script>
<script src="controllers/controllers.js"></script>
</head>
<body ng-view>
</body>
</html>
./app/app.js
'use strict';
/* App Module */
var dc4SearchApp = angular.module('dc4SearchApp', [
'ngRoute',
'dc4SearchControllers'
]);
dc4SearchApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/company-search', {
templateUrl: 'views/company-search.html',
controller: 'CompanySearchCtrl'
}).
otherwise({
redirectTo: '/company-search'
});
}]);
./app/views/company-search.html
<div ng-controller="CompanySearchCtrl">
{{test}}
<div class="spinner spin"> </div>
</div>
I am hoping this is just something silly and easy that I am over looking and haven't tried yet! Thanks in advance.
"Browsersync works by injecting an asynchronous script tag right after the body tag during initial request. In order for this to work properly the body tag must be present. Alternatively you can provide a custom rule for the snippet using snippetOptions"
https://www.npmjs.com/package/browser-sync
It seems Browsersync is reloading the body tag. Have you tried moving the ng-view to another child div ?
I am trying to create a simple Angular app and I have recently added a router in route.js. For some reason the association isn't being made between mainCtrl and someview.html The reason I know this is because the view isn't being injected in <div ng-view></div> Anyone have any idea why?
My folder structure is the following
root
------/app
----------routes.js
----------/views
-----------------someview.html
------/public
---------mainCtrl.js
---------index.html
server.js
mainCtrl.js
angular.module('LiveAPP',[])
.controller('MainCtrl', function($scope) {
$scope.Artists = [
{name:"Blink 182",age:14},
{name:"Led Zeppelin",age:12},
{name:"Lil Wayne",age:11}
];
$scope.number = 100;
});
someview.html
<div>{{number}}</div>
route.js
angular.module('LiveAPP', ['ngRoute'])
.config(function($routeProvider, $httpProvider) {
$routeProvider
.when('/', {
templateUrl : '/views/someview.html',
controller : 'MainCtrl'
})
});
index.html
<!doctype html>
<html ng-app='LiveAPP'>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js">
</script>
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-route.min.js"></script>
<script src="mainCtrl.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(3000);
console.log("Listening at 3000")
angular.module('LiveAPP',[])
.controller('MainCtrl', function($scope) {
Here, you define a module LiveAPP, that doesn't depend on any other module, and add a controller to this module.
angular.module('LiveAPP', ['ngRoute'])
.config(function($routeProvider, $httpProvider) {
And here, you redefine, once again, a module with the same name, depending on ngRoute. But since you're redefining it, you effectively overwrite the previously defined module and all its components.
A module must be defined once, and only once.
I don't know much about express, but I also don't understand why all your files are not under public, since that is apparently the directory that the web server serves.
I am having trouble setting up ng-view. This is my first mean stack app. I got everything working within index.html. However, when I set up ng-view I am getting errors stating that I have my javascripts in a public folder. My index.html is in the html folder. I have set up an additional folder in views called templates to house my additional pages
"GET http://localhost:3000/templates/home.html 500 (Internal Server Error)"
Inside of my html I have set up ng-view
<!doctype html>
<html lang="en" ng-app='myApp'>
<head>
<meta charset="UTF-8">
<title>Caffeine app</title>
<!-- styles -->
<link href="http://netdna.bootstrapcdn.com/bootswatch/3.3.2/yeti/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="stylesheets/style.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container>
<div ng-view>
</div>
</div>
<!-- scripts -->
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="libs/angular/angular.min.js"></script>
<script src="libs/angular-route/angular-route.min.js"></script>
<script src="javascripts/main2.js" type="text/javascript"></script>
</body>
</html>
In my public js folder I have set up my factory, config, and controllers. I am using swig.
var app = angular.module('myApp', ['ngRoute'], function ($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
});
app.config(function($routeProvider,$locationProvider){
$routeProvider
.when('/home',{
templateUrl:'templates/home.html',
controller:'myController'
})
.when('/drinkLibrary',{
templateUrl:'templates/drinkLibrary.html',
controller:'DrinkLibraryController'
})
.otherwise({
redirectTo: '/home'
})
$locationProvider.hashPrefix('!');
});
app.factory('Drink',function($http) {
var Drink = function(name,description,caffeineLevel) {
this.name = name;
this.description = description;
this.caffeineLevel = caffeineLevel;
}
return Drink;
})
app.controller('HomeController',function($scope){
console.log('home');
})
app.controller('DrinkLibraryController',function($scope){
console.log('drinkLibrary');
})
app.controller('myController', function($scope,Drink,$http ) {
var init = function() {
$scope.defaultForm = {
beverageName: "",
description: "",
caffeine: ""
};
}
init();
// $scope.defaultForm = defaultForm;
$scope.allDrinkList = [];
$scope.drinkList= function(obj) {
var newdrink = new Drink(obj.beverageName,obj.description,obj.caffeine);
$scope.allDrinkList.push(newdrink);
console.log($scope.allDrinkList);
init();
$http.post('/api/drinks',obj).
success(function(data){
console.log(data)
$scope.message = 'success';
}).
error(function(data){
console.log('error');
})
};
});
Inside of my routes folder I am making sure to render the index
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
In doing a mean stack I must remember to set up routes on the server and client side. My templates are in the view. I am rendering my view through express I need to also render my templates in the same manner.
app.use('templates/:templateid', routes);
I am using the express generator so through the routes I called a get request and set the url to the templates folder. Next, I identified the template id as a param. This saves me from setting up each page ex(home,library, about).
router.get('/templates/:templateid' ,function(req,res,next){
res.render('templates/' + req.params.templateid);
})