Change root of Mean application - angularjs

I am working on mean application,i have a requirement to load my html,css from another url like("/myApp") rather then root, so how can get this? i mean i want to start my app form url "localhost:3003/myApp", bydefault it is running on "localhost:3003/"
My configuration file is
var express = require('express'),
routes = require('./routes'),
fs = require('fs'),
bodyParser = require('body-parser'),
router = express.Router();
var port = 80;
var app = module.exports = express();
// Configuration
//app.use(router);
app.use(bodyParser());
//app.use(express.methodOverride());
app.use(express.static(__dirname + '/dev'));
//app.use(express.compress());
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, Content-Length,X-Requested-With");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
next();
})
router.get('/', routes.index);
router.get('/template/:name', routes.partials);
// JSON API
router.get('/api/name', routes.name);
// redirect all others to the index (HTML5 history)
router.get('*', routes.index);
app.use('/', router);
app.listen(3003, function(){
console.log("Express server listening on port mode");
});
process.on('uncaughtException', function (err) {
console.log((new Date).toUTCString() + ' uncaughtException:', err.message)
console.log(err); //process.setMaxListeners(0);
// process.setMaxListeners(0);
process.exit(1)
})

Change: app.use('/', router); to app.use('/myApp', router);

Related

MEAN-stack app: REST API calls from angular2 frontend to express backend do not work. Error: ERR_CONNECTION_REFUSED

I am building a MEAN stack app, following this tutorial: https://www.youtube.com/watch?v=PFP0oXNNveg&t=3236s
The Problem: I try to do http.get() request from my angular2 frontend to my express backend. It does not work and i get the Error: ERR_CONNECTION_REFUSED:
The Error
My frontend is on localhost/4200 and my backend on localhost/3000. I figured the problem might be that, so i search for solutions and tried everything described in here: Angular-CLI proxy to backend doesn't work (solution to proxy the localhost port), which does not work for me. I still get the error.
here is my code :
Service method with API call
getUsers() {
return this.http.get('http://localhost/3000/api/users')
.map(res => res.json());
}
server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var start = require('./routes/start');
var registration = require('./routes/registration');
var port = 3000;
var app = express();
//View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
//Set Static Folder
app.use(express.static(path.join(__dirname, 'client')));
app.use(express.static(path.join(__dirname, 'client', 'dist')));
//Body Parser MW
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', start);
app.use('/api', registration);
app.listen(port, () =>{
console.log('Server started on port '+port);
});
The route i try to use with my API call
//get all the user
router.get('/users', function(req, res, next){
db.users.find(function(err, usrs){
if(err){
res.send(err);
}
res.json(usrs);
});
});
//get single user
router.get('/user/:id', function(req, res, next) {
db.users.findOne({_id: mongojs.ObjectId(req.params.id)}, function(err, usr){
if(err){
res.send(err);
}
res.json(usr);
});
});
//save a new user
router.post('/user', function(req, res, next) {
var user = req.body;
if(!user.name || !user.password){
res.status(400);
res.json({
"error": "Bad Data"
});
} else {
db.users.save(user, function(err, user) {
if(err){
res.send(err);
}
res.json(user);
});
}
});
module.exports = router;
I'm guessing because you're trying to go to 'http://localhost/3000/api/users' which has a / after localhost instead of a :, so you're going to localhost on port 80, which is the default. Switch it to 'http://localhost:3000/api/users', does that help?

On refreshing angularjs page gives error of page not found

I have an angular application in which when I used
$locationProvider.html5Mode(true);
for removing #! , it works good. but when I refreshes the page it gives error that
Get GET /c/electronic/computer/laptop not found which is my url
This is my app.js page
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 index = require('./routes/index');
var app = express();
app.use(function(req,res,next){
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
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(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
This is my index page I putted all my functions and apis for firing queries where in models there had my mongodb's queries
var express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
Category = require('./models/category');
Product = require('./models/product');
http = require('http');
mongoose.connect('mongodb://localhost/baazaronline');
var db = mongoose.connection;
router.get('/api/category', function(req, res){
Category.getCategory(function(err, category){
if(err){
throw err;
}
res.json(category);
});
});
router.get('/api/product', function(req, res){
Product.getProduct(function(err, product) {
if(err){
throw err
}
res.json(product);
})
});
router.get('/api/product/:_id', function(req, res){
Product.getProductById(req.params._id, function(err, product){
if(err){
throw err;
}
res.json(product);
});
});
Kasun, the reason that this is occurring is because you are trying to refresh the page from one of your sub routes (has nothing to do with ui-router).
Basically if you request www.yourdomain.com/ you likely have your server setup to return index.html which bootstraps your angular app. Once the app has loaded, any further url changes take html5Mode into consideration and update your page via ui-router.
When you reload your page the angular app is no longer valid as it has not loaded yet, so if you are trying to load a sub route (for example: www.yourdomain.com/someotherpage), then your server does not know how to deal with /someotherpage and likely returns 404 or some other error.
What you need to do is configure your server to return your angular app for all routes. I primarily use node/express, so I do something like:
app.get('*', function(req, res, next) {
// call all routes and return the index.html file here
}
Note: I usually use something like this as a final catch all, however I also include other routes above it for things like requesting static files, web crawlers, and any other specific routes that need to be handled.

Angular 4 Node Mssql

I am a newbie when it comes to web development . I am currently working to get a real time web project up and running . I have a ms sql server 2014 working in my workplace and have installed node.js/ and used express generator to generate out an application . I have used mssql node module to connect and retrieve data from mssql server and it works.Although, Things that are confusing to me at this point:
how do i add angular 4 into the equation to help with the frontend development?i have already done npm install --save anular/cli but do not know where to start regarding creating input forms with drop downs whose values are to retrived from the DB .
my 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 index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 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('/users', users);
// 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;
my index.js (i tried to create a connection with myssql and display a table in the index.html jade file)
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
GetData(function(recordset)
{
res.render('index', {projects: recordset })
});
});
function GetData(callback )
{
var sql = require ('mssql');
const config = {
user: 'sa',
password: 'password',
server: 'localhost\\SQLEXPRESS',
database: 'xxxxx',
options: {
encrypt: false // Use this if you're on Windows Azure
}
};
var connection = new sql.Connection(config, function(err)
{
var request = new sql.Request(connection);
request.query('select * from Project_Type' , function(err, recordset)
{
callback(recordset);
});
});
}
module.exports = router;
Some more questions:
Is this the right place to start a sql connection ? or should i put in in the app.js file
and other advice as to how to setup the environment and angular to properly speak with the db would be highly appreciated.

How to remove # from url in AngularJS using Express framework?

I have a website which has a front-end and back-end.
I have stored my front-end files in client folder, and back-end files in admin folder. I have removed # tag from front-end URL by adding
$locationProvider.html5Mode(true);
in my client app.js file and
<base href="/">
added in client index.html file
Same thing I added in admin folder file also in index.html I added
<base href="/admin">
but still, it's not working.
Here is my server.js file
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var path = require('path');
var session = require('express-session');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/edb');
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next()
});
app.use(session({secret: 'keyboard cat', cookie: { maxAge: 60000 }, resave: true, saveUninitialized: true }))
app.use('/', express.static('app', { redirect: false }));
app.get('/', function (req, res, next) {
res.sendFile(path.resolve('client/index.html'));
});
I have tried adding this to the server.js file
app.get('/admin', function (req, res, next) {
res.sendFile(path.resolve('admin/index.html'));
});
but it's taking to client index.html file.
Do you have a solution?
I got a solution
app.get('/*', function (req, res, next) {
res.sendFile(path.resolve('client/index.html'));
});
app.get('/admin/*', function (req, res, next) {
res.sendFile(path.resolve('admin/index.html'));
});
I added this code in server.js file
its work like a charm

Angularjs CORS trouble with Node, Express, Oauth2, and Passport

Recently we have decided to switch our front-end from EJS to Angular separate the frontend and the backend completely. In doing so, we started to run into several issues across multiple browsers. On the back end we are using Node with express along with passport and oauth2. For the front end we are attempting to use angular. EJS works using express.render, but we would prefer to use angular directly by utilizing express as just a RESTful API.
I'm running both the backend and frontend locally at localhost:8080 and localhost:3000, respectfully. When just working with the backend (USING EJS, NOT ANGULAR), I can successfully go to our backend port in the browser, login via passport-oauth, and be redirect to the account page (from the providers login screen) where my json data is rendered via res.json. The problem is I am unable to do this from the frontend UI after removing EJS.
I've tried configuring CORS a dozen different ways while using three different browsers with no luck. The following three snippets are the errors I'm getting in the browsers console while trying to access localhost:8080 from the frontend via $http and $resource (see below for the code). The image below the three code snippets is what the node console is telling me when trying to access port 8080 from each different browser...
Chrome:
XMLHttpRequest cannot load 'PROVIDER-DETAILS-URL'. No 'Access-Control-Allow- Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Firefox:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at 'PROVIDER-DETAILS-URL'. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at 'PROVIDER-DETAILS-URL'. (Reason: CORS request failed).
Safari:
XMLHttpRequest cannot load http://localhost:8080/auth/PROVIDER. Request header field Accept-Encoding is not allowed by Access-Control-Allow-Headers.
Console Image:
And the code:
Server:
app.js
'use strict';
const express = require('express');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const logger = require('morgan');
const errorHandler = require('errorhandler');
const path = require('path');
const flash = require('connect-flash');
const passport = require('passport');
const expressValidator = require('express-validator');
/**
* Load environment variables, where API keys and passwords are configured.
*/
const config = require('./config/config');
/**
* Route Handlers
*/
const index = require('./routes/index');
const account = require('./routes/account');
const logout = require('./routes/logout');
/**
* API keys and Passport configuration.
*/
const passportConfig = require('./strategy');
/**
* Create Express server.
*/
const app = express();
/**
* Express configuration.
*/
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.header("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT");
next();
});
app.use(cookieParser());
app.use(expressValidator());
app.use(session({
resave : true,
saveUninitialized : true,
secret : config.sessionSecret,
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
/**
* Primary app routes.
*/
app.get('/', index.execute);
app.get('/account', passportConfig.isAuthenticated, account);
app.get('/logout', logout.execute);
/**
* OAuth authorization routes.
*/
app.get('/auth/PROVIDER', passport.authenticate('PROVIDER'));
app.get('/auth/PROVIDER/callback', passport.authenticate('PROVIDER', { failureRedirect : '/'}), function(req, res) {
res.redirect('/account');
});
/**
* Error Handler.
*/
app.use(errorHandler());
/**
* Start Express server.
*/
app.listen(8080, () => {
console.log('App listening on port 8080');
});
module.exports = app;
strategy.js
'use strict';
const passport = require('passport');
const session = require('express-session');
const config = require('./config/config');
const OAuth2Strategy = require('passport-oauth').OAuth2Strategy;
/**
* Put together the right header info for PROVIDER
*/
var authString = new Buffer(config.PROVIDER.clientID + ':' + config.PROVIDER.clientSecret);
var customHeader = {
"Authorization": "Basic " + authString.toString('base64')
};
/**
* OAuth2Strategy containing the customHeader created above.
*/
passport.use('PROVIDER', new OAuth2Strategy({
authorizationURL : config.PROVIDER.authorizationURL,
tokenURL : config.PROVIDER.tokenURL,
clientID : config.PROVIDER.clientID,
clientSecret : config.PROVIDER.clientSecret,
callbackURL : config.PROVIDER.callbackURL,
customHeaders : customHeader,
passReqToCallback : true
},
function( req, accessToken, refreshToken, profile, done ) {
req.session.accessToken = accessToken;
return done(null, profile);
}
));
passport.serializeUser(function(user, done) {
return done(null, user);
});
passport.deserializeUser(function(obj, done) {
return done(null, obj);
});
/**
* Login Required middleware.
*/
exports.isAuthenticated = function(req, res, next) {
if (req.isAuthenticated()) {
console.log('isAuthenticated');
return next();
}
res.redirect('/');
};
/**
* Authorization Required middleware.
*/
exports.isAuthorized = function(req, res, next) {
var provider = req.path.split('/').slice(-1)[0];
if (_.find(req.user.tokens, { kind: provider })) {
next();
} else {
res.redirect('/auth/' + provider);
}
};
index.js
exports.execute = function (req, res) {
if (req.user) {
console.log('========== ROUTES/INDEX.JS | 3 ==========');
res.redirect('/account');
} else {
console.log('========== ROUTES/INDEX.JS | 6 ==========');
res.redirect('/auth/PROVIDER');
}
};
Client:
I combined this to make it a little easier to read.
angular.module('StackOverflowPost', [])
.factory('APIService', function() {
function getData( $q, $http ) {
var defer = $q.defer();
$http.get( 'localhost:8080' )
.success( getDataComplete )
.catch( getDataFailed );
function getDataComplete( response ) {
console.log( response.Authorization );
defer.resolve(response.data.results );
}
function getDataFailed( error ) {
console.log( error.data );
defer.reject( 'XHR Failed for getData - ' + error.data );
}
return defer.promise;
}
})
.controller('MainCtrl', function( APIService ) {
var vm = this;
vm.getDataTest = function() {
APIService.getData().then(function( returnedData ) {
console.log( returnedData );
})
}
});
Any help or direction would be greatly appreciated.
UPDATE (4/28/2016): I updated the original post with more details. I also updated the code to what it is after another week of trial and error.
Please check this
https://gist.github.com/dirkk0/5967221
Code should be
// in AngularJS (client)
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
// in Express/nodeJS
// in NodeJS/Express (server)
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, POST","PUT");
next();
});

Resources