404 while importing external scripts angular - javascript

I am trying to include Angular module as a separate file.
Here is my app.js
var app = angular.module('app', ['ngRoute']);
app.controller("TodoController", function($scope) {
$scope.players = ["Tom", "Dick", "Harry"];
});
This is my index.html
<html ng-app="app">
<head>
<title>Hello Angular!</title>
</head>
<body ng-controller="TodoController">
<input type="text" name="" ng-model="name"> {{name}}
<ul>
<li ng-repeat="player in players">
{{ player }}
</li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular-route.min.js"></script>
<script src="scripts/app.js"></script>
</body>
</html>
I am using express with node. This is my server.js
var express = require('express');
var app = express();
var path = require('path');
var port = process.env.PORT || 5000;
app.get('/', function(req, res){
//res.sendfile('./index.html');
res.sendFile('index.html', { root: path.join(__dirname) });
});
app.listen(port);
console.log('Express app is listening on : ' + port);
When I am trying to execute I am getting http://localhost:5000/scripts/app.js 404 (Not Found)
Code is working well when everything put in to the index.html.
File Structure is like this.
-- index.html
-- server.js
-- scripts
-- app.js

I have found the solution. as mentioned on the comment issue was with Serving static files in Express. I have included this code to the server.js.
app.use(express.static('public'))
I also created the public folder and included app.js to the public folder.
My new code looks like this.
public/index.html
<html ng-app='app'>
<head>
<title>Hello Angular!</title>
</head>
<body ng-controller="TodoController">
<input type="text" name="" ng-model="name"> {{name}}
<ul>
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.completed">
{{todo.title}}
</li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular-route.min.js"></script>
<script type='text/javascript' src="app.js" charset="UTF-8"></script>
<script type='text/javascript' src="app/controllers/TodoController.js" charset="UTF-8"></script>
</body>
</html>
Server.js
var express = require('express');
var app = express();
var path = require('path');
var port = process.env.PORT || 5000;
app.get('/', function(req, res){
res.sendFile('index.html', { root: path.join(__dirname, 'public') });
});
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port);
console.log('Express app is listening on : ' + port);
public/controllers/TodoController.js
app.controller('TodoController', ['$scope', function ($scope) {
$scope.todos = [
{ title: 'Learn Javascript', completed: true },
{ title: 'Learn Angular.js', completed: false },
{ title: 'Love this tutorial', completed: true },
{ title: 'Learn Javascript design patterns', completed: false },
{ title: 'Build Node.js backend', completed: false },
];
}]);
public/app.js
var app = angular.module('app', []);
New file structure will be like this.
-- public
-- app
-- controllers
-- TodoController.js
-- app.js
-- index.html
-- server.js
-- package.json

Since you have only http://localhost:5000/ route which is exposed which renders index.html file.
app.get('/', function(req, res){
//res.sendfile('./index.html');
res.sendFile('index.html', { root: path.join(__dirname) });
});
Any other path will give you 404.
You cannot access http://localhost:5000/scripts/ directly.
To access scripts please add the following line in server.js
app.use(express.static(path.join(__dirname, 'scripts')));
Updated code for server.js will be.
var express = require('express');
var app = express();
var path = require('path');
var port = process.env.PORT || 5000;
app.use(express.static(path.join(__dirname, 'scripts')));
app.get('/', function(req, res){
//res.sendfile('./index.html');
res.sendFile('index.html', { root: path.join(__dirname) });
});
app.listen(port);
console.log('Express app is listening on : ' + port);
Now http://localhost:5000/scripts/app.js should not give 404.
Not just scripts/app.js, You can access any file which is in scripts folder now.

Related

How to refer a css file from index.html in React

I have a folder called assets which have a styles.css and then I have index.html which I would want to reference styles.css but for some reason it can't.
My current solution is this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>My App</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="/bundle.js"></script>
</body>
</html>
And I have the node server running like this:
var webpack = require("webpack");
var config = require("./webpack.config.js");
var http = require('http');
var express = require('express');
var app = express();
var proxy = require('http-proxy-middleware');
var path = require('path');
const compiler = webpack(config);
app.use(require("webpack-dev-middleware")(compiler, {
noInfo: true,
publicPath: "/"
}));
app.use(require("webpack-hot-middleware")(compiler));
app.use('/auth', proxy('http://localhost:8081', {changeOrigin: true}));
app.use('/api', proxy('http://localhost:8081', {changeOrigin: true}));
app.get("*", function(req, res) {
res.sendFile(__dirname + '/index.html');
});
/**
* Anything in public can be accessed statically without
* this express router getting involved
*/
app.use(express.static(path.join(__dirname, 'assets'), {
dotfiles: 'ignore',
index: false
}));
var server = http.createServer(app);
server.listen(3000, function() {
console.log("express listening at localhost:3000");
});
This is not working for me it cannot find the css file, how can I make it so I can reference the css file from index.html. Also I have index.js on my src folder which is used as an entrance file for running the whole React App.
Add the route for styles.css before app.get("*",...)
app.get("/styles.css", function(req, res) {
res.sendFile(__dirname + '/styles.css');
});

Dont find socket.io

Files
chat
node_modules
web
public
css
estilo.css
img
tiempo.jpg
js
script.js
view
vista.html
app.js
package.json
JSON
{
"name":"chat",
"version":"0.0.1",
"privte":"true",
"dependencies":{
"socket.io":"1.4.8",
"express": "4.14.0"
}
}
In the File vista.html I can't open or load the soket.io, but I can load the files: pictures, css, js - don't have a problem with that. The problem is to try to load soket.io
NODE.js File, app.js
var express = require("express"),
app = express(),
http = require("http").Server(app),
io = require("socket.io")(http),
nicknames=[],
users={};
app.listen(3000, function () {
console.log('SERVIDOR LISTO');
});
app.use(express.static(__dirname + '/web/public'));
app.get("/",function(req, res){
res.sendFile( __dirname+'/web/public/view/index.html');
});
io.sockets.on("connection", function(socket){
.......
.......
}
and my html file is
<html>
<head>
<title></title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<img src="http://localhost:3000/img/tiempo.jpg"
alt="Smiley face" height="30%" width="30%">
</body>
</html>
I found the solution to my problem. I had to reorder the code, what starts first and finish with the last.
var express = require('express'),
app = express(),
io = require('socket.io'),
nicknames=[],
users={};
var server=app.listen(3000, function () {
console.log('SERVIDOR LISTO');
});
var mysocket = io.listen(server);
app.use(express.static(__dirname + '/web/public'));
app.get("/",function(req, res){
res.sendFile( __dirname+'/web/public/view/index.html');
});

Nodejs/Express with Angular - 404 error

I've been trying to learn the MEAN stack and wanted to do an application to test it out. The aim was to have a static variable (in this case 'hello') displayed by Angular in the HTML, I can't seem to get my $scope variable in my controller to display, having looked in the developer console on my browser I saw 'GET 127.0.0.1:3000/app.js 404 not found'.
This is my node server using express:
var express = require('express');
app = express();
app.get('/', function(req, res){
res.sendFile(__dirname + '/views/index.html');
});
app.listen(3000, function() {
console.log('I\'m listening on port 3000...');
});
This is my index.html file (a directory below in /views):
<!DOCTYPE html>
<html ng-app="myModule">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/
angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<h1>Sucess!</h1>
<div ng-controller="myController">
<p>Angular test: {{ message }}</p>
</div>
</body>
And this is my app.js file containing my module and controller (also in /views):
var myApp = angular.module('myModule', []);
myApp.controller('myController', ['$scope',
function($scope) {
$scope.message = 'hello';
}]);
I'd be very grateful if anyone could help out!
You will have to serve all the files, for example using express.static, not just index.html:
var express = require('express');
app = express();
app.use(express.static('views'));
app.listen(3000, function() {
console.log('I\'m listening on port 3000...');
});

Best way to integrate NodeJS with Angular

I'm trying to make a web application that uses a Node server as the back end and Angular to take information from the Node server and create a responsive front end. Currently, in my simple application, I have two js files: server.js and controller.js. Here is the code for each file:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var port = 8006;
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/data', function(req, res){
console.log(req.body);
res.send("Success!")
res.status(200);
res.end();
});
app.listen(port);
console.log("Server running on port " + port);
And here's the controller file:
(function(){
var app = angular.module("testApp", []);
var TileController = function($scope){
// add stuff to $scope as initilization
};
app.controller("TileController", ["$scope", TileController]);
})();
This code is sort of incomplete because I'm not sure where to go with it, but I know what I want to do with it.
The model that Angular uses is going to be constantly updated by information parsed by the Node server upon incoming HTTP requests (specifically POST). Node is going to handle these requests and somehow pass the data along to Angular (in the controller.js file), which is going to update the model, and update the view along with that.
My question is what is the best way to pass information along from the Node server to the controller.js and update the model/view when the information is added?
I made a very simple example using just HTTP requests, and $interval, which is angular's equivalent of window.setInterval.
Save all the files in a folder
Download the node modules (express, body-parser)
node server.js
open index.html
POST some data to server (http://localhost:3000)
index.html should show a list of every data that was POST'd to the server, delayed by ~3 seconds
server.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var arr = [];
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function(req, res) {
res.json({arr: arr});
});
app.post('/', function(req, res) {
console.log(req.body);
arr.push(req.body);
res.end('Data received');
})
app.listen(3000, console.log.call(console, 'Server started.'));
app.js (angular)
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $interval, $http) {
$scope.arr = [];
var stop = $interval(function() {
$http.get('http://localhost:3000')
.then(function(res) {
$scope.arr = res.data.arr;
}, function(e) {
console.error(e);
});
}, 3000);
});
index.html
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta content="UTF-8">
<title>live data example</title>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in arr">{{item}}</li>
</ul>
</body>

Configuring Express and Angular

I'm trying to make a simple Angular/Express todo-list app, and I ran into quite a bit of trouble. It's still in the works, but when I ran the code below on localhost:3000 I ended up getting {{ thing }} literally printed in the webpage.
My file paths are:
app
js
app.js
index.html
node_modules (here lies angular, express, etc)
index.js
package.json
Here is my code for index.html:
<!DOCTYPE html>
<html lang="en" ng-app='testApp'>
<head>
<meta charset="UTF-8">
<title>Angular-Express Test App</title>
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js"></script>
<script type='text/javascript' src='js/app.js'></script>
</head>
<body ng-controller='TestCtrl'>
<table>
<thead>
<tr>
<td>Item</td>
<td>Remove</td>
</tr>
</thead>
<tbody>
<tr ng-repeat='item in items'>
<td>{{ item }}</td>
<td>Done?</td>
</tr>
</tbody>
</table>
</body>
</html>
Here is my code for index.js:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.set('port', process.env.OPENSHIFT_NODEJS_PORT || 3000); //yes I plan to deploy to OpenShift
app.set('ipaddr', process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1");
app.get('*', function(req, res){
res.sendFile(__dirname + '/app/index.html', res);
});
http.listen(3000, function () {
'use strict';
console.log('Express server listening on IP: ' + app.get('ipaddr') + ' and port ' + app.get('port'));
});
And app.js:
angular.module('testApp', ['ngRoute'])
.controller('TestCtrl', [$scope, function ($scope) {
'use strict';
$scope.items = ["foo", "bar"];
}]);
Here's a screenshot of what I see, though there really isn't much in it that I haven't mentioned already...: http://puu.sh/gyhjT/684fa116f7.png
I spent a ridiculous amount of time trying to figure out what went wrong, so any help at all would be greatly appreciated!
there are few mistakes in your code,
first , the major one, you are directing every request to index page, so no way to get js/app.js
so change:
app.get('*', function(req, res){
res.sendFile(__dirname + '/app/index.html', res);
});
to:
app.get('/', function(req, res){
res.sendFile(__dirname + '/app/index.html', res);
});
app.get('/js/:file', function(req, res){
res.sendFile(__dirname + '/app/js/'+req.params.file, res);
});
next is, ngRoute and $scope mistake, ngRoute is not part of angular.min.js, you have to include it seperately, for now, i just changed your js/app.js and it works for me
angular.module('testApp', [])
.controller('TestCtrl', ['$scope', function ($scope) {
'use strict';
$scope.items = ["foo", "bar"];
}]);
remove ['ngRoute'] because you don't use it. If you want to use, please include angular-route.js in head

Categories