Configuring Yeoman for building non-root projects - angularjs

I might be missing something obvious, but i really can't figure it out by going over the docs and issues on GitHub -
I'm developing an AngularJS project that will be deployed on a specific sub-directory on the server (i.e not the root).
I'm using Yeoman.io, and trying to configure it so the app is self-contained and doesn't rely on absolute paths like '/images' and so on.
Every attempt to mess around with the Grunt file or Compass config ends up with a broken build. Paths of images and sprites are wrong - sometimes it's a wrong directory and sometimes wrong filename (no revision prefixes).
Anyone had good experience with that?

So if I understand you correctly, you want to serve your angular project on a specific path on system.
In grunt.js, I've registered a server task which starts my (local) server:
grunt.registerTask('server', 'Start server', function() {
var done = this.async();
var app = require('./app.js');
var http = require('http');
// Start server
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
}).on('close', done);
});
app.js contains the server config:
var express = require('express'),
path = require('path');
var app = module.exports = express();
// Configuration
app.configure(function () {
app.set('port', process.env.PORT || 4000);
app.use(express['static'](path.join(__dirname, 'dist')));
});
In my example I serve the project on directory dist, but this can be anything.

Related

Integrate and serve React-Admin from existing Express application

In my project I need an administrator application. I have stumbled upon the admin-react. It seems it does exactly what I need it to do. I have checked their tutorial. Made some drafts, and got it running (following tutorial).
However I have an Express application that has routes and API's already working, and also I have React application served by the Express one. I would like to serve the Admin-React instead, in other words remove the existing React application and start customizing the React-Admin one as a static resource. Simply, my existing Express application should serve the React-Admin and expose the existing API's to it.
Looking at the tutorials, I found no information how to do it. It had yarn start and it starts running on port 3000.
I am missing something here very basic it seems.
Is there an example of that setup?
This is my Express.js that already serves React application (not React Admin) from public folder.
'use strict';
/* jshint camelcase:false */
require('dotenv').config();
if (process.env.NODE_ENV === undefined) {
throw new Error('No environment variable was set. For development use [export NODE_ENV=dev].');
}
let express = require('express');
var favicon = require('serve-favicon');
let path = require('path');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let expressValidator = require('express-validator');
let configuration = require('./app/Configuration');
let app = configuration.getApp();
let config = configuration.getParameters();
let errorHandler = require('./src/Error/Handler');
let session = require('client-sessions');
app.use(require('./src/Twig/ExtendWithCustomFunctions').extend());
app.use(session({
cookieName: 'session',
secret: 'xxxxxxx',
duration: 12 * 60 * 60 * 1000,
activeDuration: 2 * 60 * 60 * 1000
}));
app.use(bodyParser.json());
app.use(errorHandler.bodyParser);
app.use(expressValidator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(favicon(__dirname + '/public/favicon.ico'));
configuration.setErrorHandler(errorHandler);
configuration.initializeControllers(__dirname);
configuration.initializeErrorHandling();
module.exports = app;
The only way to serve a React Admin from an Express endpoint is to build it first.
If you followed the tutorial, you should have run a create-react-app application, so you can run the following command to bundle your app:
npm run build
# or
yarn build
Your bundle files will be available under the static folder.
Then, you can move these files to your express app, in a subfolder, where you'll be able to serve them with express.static.
More info about the create-react-app build & deployement: https://facebook.github.io/create-react-app/docs/deployment
There is even an example of how to serve the build: https://facebook.github.io/create-react-app/docs/deployment#other-solutions

socket.io - polling-xhr.js:264 GET error

I've been working on my chat application on my localhost machine (which works fine), but when I'm trying to host it on Github or 000webhost, I get this error polling-xhr.js:264 on both hosts (both hosts have an https connection). I am using cfenv to parse Cloud Foundry-provided environment variables. Here is a picture of the error in question:
It'll keep going like that...
Here is a look at my code:
server.js
var cfenv = require('cfenv');
var appEnv = cfenv.getAppEnv();
var express = require('express');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(appEnv.port, appEnv.bind, function(){
console.log("Server starting on " + appEnv.url);
})
app.use(express.static(__dirname + '/'));
... // rest of socket.io code
index.html
...
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
...
socketService.js (btford's socket.io extension)
app.factory('socket', function(socketFactory){
return socketFactory();
});
I've tried various code suggested here on StackOverflow, but I can't seem to get it right. My code works very well with localhost, but it doesn't work when there is an actual server such as one mentioned above.
Thanks a lot for the help!
both hosts have an https connection
But you have in your server code:
require('http');
Try using the https module instead of http. That might explain why the app only works in localhost. Hope this helps :)
EDIT
You should also verify that your server is listening on port 443 instead of 80
I just found out from a good friend that the servers I was hosting on does not support node.js and that's why it didn't work. When my friend hosted his server with it installed, it worked very nice.

A second node server (or port) won't start in production (Elastic Beanstalk)

I have a Node/Angular app I'm trying to deploy. It uses two node servers: One to essentially serve the app; another to get data from an API, when a specific port is requested by the app, and store that data locally.
I've got it working perfectly on my own local machine. However, when I deploy to production environments -- either Heroku or AWS Elastic Beanstalk -- I find that the second script either won't run or won't start properly. The end result is, it doesn't get the data I need.
Here are the two scripts; they're both set to run in package.json under "start": "node main.js & node node-server.js"
main.js (again, this one seems to be serving the app just fine):
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/app'));
app.listen(process.env.PORT || 3000);
node-server.js (the one that doesn't seem to work; no data is gathered or populated in the app):
var http = require('http');
var port2 = 1234
var fs = require('fs');
//We need a function which handles requests and send response
function handleRequest(req, res) {
request.get({
url: 'http://sample-url.json',
qs: {
url: 'http://sampletool/pb/newsletter/?content=true'
}
}, function (err, result) {
res.end(result.body);
fs.writeFile('app/data.json', result.body, function (err) {
if (err) return console.log(err);
console.log('API data > data.json');
});
});
}
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(port2, function () {
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://0.0.0.0:%d", port2);
});
Then, the main Angular app calls this port (http://0.0.0.0:1234) when the page is loaded, to request new data.
Elastic Beanstalk is using nginx, something I'm not super familiar with and that I don't have running on my local.
Is there something big I'm missing in configuring multiple node.js servers to be running on different ports in a production environment? Thanks in advance for any help.
For security reasons, cloud service providers typically allow the usage of only one port (which is dynamically and randomly assigned to the PORT environment variable) for an application to use from a node server. Read this section from Heroku documentation to understand more about this.
This is why the main app (main.js) that uses process.env.PORT is working and the other app (node-server.js) that uses hard-coded 1234 is not.
This question has some pointers about the feasibility of multiple ports on Heroku (though, there is no good news there, I am afraid).
As how to go about fixing this, one thing that could be tried is to split this into two separate apps that are deployed separately with separate package.json etc.

Webpack dev server run on different port

So I have IIS serving up my WebApi and AngularJS project on port 80, using a the alias mywebsite.local-dev.com in the hosts file.
I have webpack config setup for bundling, all I want to do now is stick webpack dev server over the top so that when I modify a file it re bundles everything and updates the browser.
I have browser-sync nearly working but require('./somehtmltemplate.html') seems to be causing issues. It's an Angular app so I use require in the ui-router template property. Here is my gulpfile:
var gulp = require('gulp'),
browserSync = require('browser-sync').create(),
watch = require('gulp-watch'),
webpack = require('webpack'),
webpackconfig = require('./webpack.config');
gulp.task("webpack", function(callback) {
// run webpack
webpack(
webpackconfig,
function(err, stats) {
if(err) throw new gutil.PluginError("webpack", err);
callback();
}
);
});
gulp.task('watch', function() {
browserSync.init({
proxy: "mywebsite.local-dev.com"
});
gulp.watch("App/**/*.js", ['webpack']).on('change', browserSync.reload);
gulp.watch("App/**/*.html", ['webpack']).on('change', browserSync.reload);
});
My question is, how do I get either one working.
edit
Because I am using .cshtml I can't use webpack-dev-server. So the question is, how can I get gulp working?
I solved a similar problem by having Browsersync proxy my external server (MAMP in my case, but it shouldn't matter) while using webpack-dev-middleware and webpack-hot-middleware as middleware on the proxy. With that setup, you can have your normal server take care of serving your app, and Browsersync+Webpack will just handle asset bundling & serving, and browser injections & reloads.
Here's a working example if you're interested: github.com/shanecav/webpack-browsersync-proxy

How to use express.js as proxy in angularjs-seed app

angularjs newbie alert!!!
I need to a proxy to avoid CORS & i'm looking to implement express-proxy. I found this solution but I'm not sure where to put the code. I need the information in the context of a typical angular-seed app. Please help. Thank you!
ex: Where do I put in the code & how do I start the proxy server
var express = require('express'),
httpProxy = require('http-proxy'),
app = express();
var proxy = new httpProxy.RoutingProxy();
function apiProxy(host, port) {
return function(req, res, next) {
if(req.url.match(new RegExp('^\/api\/'))) {
proxy.proxyRequest(req, res, {host: host, port: port});
} else {
next();
}
}
}
app.configure(function() {
app.use(express.static(process.cwd() + "/generated"));
app.use(apiProxy('localhost', 3000));
app.use(express.bodyParser());
app.use(express.errorHandler());
});
module.exports = app;
I'm not sure what your exact setup is, but if you follow the templating from a scaffolding solution like yo, this code would go in the root directory under a file called, let's say, server.js. To start the server, to to the directory in the command line and type node server.js (or you can use gruntas a task runner if it is installed with your project). Lastly, just open your browswer to localhost:3000 and you should be all good to go.

Resources