I can't seem to use Express.js to serve up my frontend Angular2 app. It just keeps serving index.html as text and the scripts don't appear to load.
Steps to reproduce:
npm install angular-cli -g
ng new ng2app && cd ng2app
npm install express --save && npm install
touch src/server.js
update server.js file
// src/server.js
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html')
})
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
Run the server
node src/server.js
# => Node app is running on port 5000
http://localhost:5000/
Problem
browser spits this out on the page and never does anything (i.e it doesn't load my front-end angular2 app)
{{#unless environment.production}} {{/unless}} Loading... {{#each scripts.polyfills}}{{/each}}
also on this page there are the following browser console errors
GET http://localhost:5000/ember-cli-live-reload.js
(index):19 GET http://localhost:5000/%7B%7B.%7D%7D
(index):21 Uncaught ReferenceError: System is not defined
What am I doing wrong? P.S there's nothing wrong with the angular front-end portion. I know this because doing npm start works and ng2app loads up just fine like its supposed to.
This is the minimum that I have from a seed project see: https://github.com/spboyer/quickstart-ng-cli
var express = require('express'),
path = require('path'),
fs = require('fs');
var app = express();
var staticRoot = __dirname + '/';
app.set('port', (process.env.PORT || 3000));
app.use(express.static(staticRoot));
app.use(function(req, res, next){
// if the request is not html then move along
var accept = req.accepts('html', 'json', 'xml');
if(accept !== 'html'){
return next();
}
// if the request has a '.' assume that it's for a file, move along
var ext = path.extname(req.path);
if (ext !== ''){
return next();
}
fs.createReadStream(staticRoot + 'index.html').pipe(res);
});
app.listen(app.get('port'), function() {
console.log('app running on port', app.get('port'));
});
To me it looks like you have not actually ran the angular cli build.
Related
I wrote a program of node js on Brackets Text Editor and saved it with name first.js. When I am executing it with command prompt using -
node first.js
var http = require('http');
function onRequest(req,res)
{
res.writeHead(200,{'Content-Type':'text/plain'});
res.write('hello js');
res.end();
}
http.createServer(onRequest).listen(8080);
It is running fine but when I am trying to run it on the localhost, it is not working.
The program that I wrote was -
If you did try localhost:8080 and that still doesn't work, it could be that some other program is running on that port. Try .listen(3000) then visit localhost:3000.
you can create a simple http server using express (be sure that u have the packaged installed , you can install express using npm : npm install express) .
your server.js code is :
const express = require("express");
const app = express();
const port = process.env.PORT || 4000;
app.get("/", (req, res) => {
console.log("response");
});
app.listen(port, () => {
console.log("Server listining on port ", port);
});
lets say you save this file in c:/folder , open cmd in the same folder
run : node server.js .
now go to your browser and check : http://localhost:4000/
I have an express server setup online which loads multiple ports and those ports are setup on subdomains for example. port 9000 loads the main domain.com port 8000 loads the main application at "app.domain.com" port 1000 loads "signup.domain.com" and the build version of the app is on port 8500 "build.domain.com".
The application is an Angular application however when I go to load the Angular app it loads on port 4200 or it says 8500 is in use. So currently I am loading that in express like so:
// Build Application - In Development
var appbuild = express();
appbuild.get('/', function (req, res){
res.sendFile('/app/build/myapp/src/index.html', { root: '.' })
});
var port = 8500;
appbuild.listen(port);
console.log('Build App Listening on port', port);
So my question is in Express how can I instead of writing sendfile command make it launch the angular app in that location on port 8500 so my subdomain names will work. The reason I'm asking this is because right now all it does is load the index file but angular or the app isn't running so i just see source code that says app-root and a blank white page.
Thank you in advance.
Robert
--- Update. I've decided to post the entire Express file. My issue is trying to load a angular app on port 8500 from the subfolder upon booting of express. Here is the full server.js code:
// server.js
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose'),
config = require('../config/DB');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB).then(
() => {console.log('Database is connected') },
err => { console.log('Can not connect to the database'+ err)}
);
// Main Website
var web = express();
web.get('/', function (req, res){
res.sendFile('/web/index.html', { root: '.' })
});
var port = 9000;
web.listen(port);
console.log('Web Listening on port', port);
// Main Application
var app = express();
app.get('/', function (req, res){
res.sendFile('/app/index.html', { root: '.' })
});
var port = 8000;
app.listen(port);
console.log('Main App Listening on port', port);
// Build Application - In Development
var appbuild = express();
appbuild.get('/', function (req, res){
res.sendFile('/app/build/myapp/src/index.html', { root: '.' })
});
var port = 8500;
appbuild.listen(port);
console.log('Build App Listening on port', port);
// Sign up Portal
var sign = express();
sign.get('/', function (req, res){
res.sendFile('/signup/index.html', { root: '.' })
});
var port = 10000;
sign.listen(port);
console.log('Sign Up Portal Listening on port', port);
Refer to this link https://malcoded.com/posts/angular-backend-express
Update your code to the following:
const express = require('express');
const app = express();
app.listen(8500, () => {
console.log('Server started!');
});
You need to build the angular app if your angular version not 1.x
ng build
Also, I think this question is similar to your question:
Not able to view Angular app via express/heroku?
I have installed node(v4.1.2) and express(4.13.3)
Node Server code:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
After running the node file and upon calling http://localhost:3000/ gives me ERR_CONNECTION_REFUSED.
Have you run in powershell at server directory?
node app.js
You are listening on port 3000.
So Try http://localhost:3000
At first install Node.js body parsing middleware.
Installation: npm install body-parser
Then add the following lines:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
I think your problem will be solved. For more details, visit -
http://expressjs.com/en/resources/middleware/body-parser.html
When run nodejs project, the message like Unresponsive script
I got one project on git-hub based on angularjs-rickshaw. It is based on nodejs, bower.
Project: ngyewch/angular-rickshaw
Demo of above project: DEMO
I want to run above project on my local system. I successfully installed every thing (nodejs, npm, bower). But When I type http://localhost:3000/ I get nothing, I am new in Nodejs, please help me on this. What will be the correct url?
[neelabh#localhost angular-rickshaw]$ node server.js
connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0
Server running at http://localhost:3000/
I am getting following type of message if I ran 1.http://localhost:3000/ or 2. http://localhost:3000/#/home
server.js
'use strict';
var fs =require('fs'); //for image upload file handling
var express = require('express');
var app = express();
var port =3000;
var host ='localhost';
var serverPath ='/';
var staticPath ='/';
//var staticFilePath = __dirname + serverPath;
var path = require('path');
var staticFilePath = path.join(__dirname, serverPath);
// remove trailing slash if present
if(staticFilePath.substr(-1) === '/'){
staticFilePath = staticFilePath.substr(0, staticFilePath.length - 1);
}
app.configure(function(){
// compress static content
app.use(express.compress());
app.use(serverPath, express.static(staticFilePath)); //serve static files
app.use(express.bodyParser()); //for post content / files - not sure if this is actually necessary?
});
//catch all route to serve index.html (main frontend app)
app.get('*', function(req, res){
res.sendfile(staticFilePath + staticPath+ 'index.html');
});
app.listen(3000, function () {
console.log('Server running at http://' + host + ':' + port + '/');
})
//app.listen(port);
//console.log('Server running at http://'+host+':'+port.toString()+'/');
Looking at https://github.com/ngyewch/angular-rickshaw/blob/gh-pages/server.js, console.log('Server running at http://'+host+':'+port.toString()+'/') should be a callback to listen call. Otherwise console.log always gets executed, even if the server doesn't start properly.
The correct way is:
app.listen(3000, function () {
console.log('Server running at http://' + host + ':' + port + '/');
});
For staticFilePath and in other path-related parts you should use path.join:
var path = require('path');
var staticFilePath = path.join(__dirname, serverPath);
Ultimately it's best to move all static files to public directory and serve it with express.static middleware:
'use strict';
var express = require('express');
var app = express();
var port = 3000;
app.use(express.static('public'));
app.listen(port, function () {
console.log('Server running at http://' + host + ':' + port + '/');
});
I am using Express 4.2.0 and node.js 0.10.12.
The weird thing is that I created a project in C\program files\node\nodetest and when I did npm start I got no errors.
Now I created a project in C\program files\node\secondtest and when I do npm start I get
app.set('port' , process.env.port 3000) typeerror object #<object> has no method 'set' at object.<anonymous> and its pointing in C\program files\node\secondtest\bin\www:5:5
Truth is , I dont know how to deal with this error, because I dont get what it means. Is it because both my projects listen on port 3000?
I just started secondtest , I installed succesfully the dependencies with npm install and added this in app.js
var http = require('http');
var express = require('express');
var app = express();
http.createServer(app).listen(3000, function() {
console.log('Express app started');
});
app.get('/', function(req, res) {
res.send('Welcome!');
});
Thanks
EDIT
If I leave the default code in app.js and www I get no errors. If I replace the default code of app.js with mine, and I remove the
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
part from www, then I get no errors.
Because I guess app.set and app.get are depricated in express 4.2.0? Or because when I set an http server in my app.js code, conflicts the default www code? Either one of these, or I am really confused.
EDIT 2
This is the default code of the www
#!/usr/bin/env node
var debug = require('debug')('secondtest');
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
Updated answer according to the updated question.
Since you're calling www and its code needs to set the port and listen to it, your secondtest code should not listen to the port. Instead it should export the Express app as follows:
// ...
module.exports = app;
The www will do the listening part.
Otherwise, the secondtest tries to start listening on a port while not exporting the Express app, and www tries to listen again on a variable app which is not an Express app, thus the error object #<object> has no method 'set'.
When you do var app = require('../app'); in another script, it is important so that this ../app script actually exports the Express app.
Old answer.
Do node app.js instead of using npm command.
Second, make sure the same port is not used by both processes at the same time. You can't listen to the same port unless you're in cluster mode.
Considering the following is the content of both firsttest and secondtest:
var http = require('http');
var express = require('express');
var app = express();
http.createServer(app).listen(process.env.port || 3000, function() {
console.log('Express app started');
});
app.get('/', function(req, res) {
res.send('Welcome!');
});
Do the following to start both apps:
Terminal 1: (the first app will default to port 3000).
$ node firsttest/app.js
Terminal 1:
$ export PORT=3001
$ node secondtest/app.js