Nodejs Express 4 routes not working after changing server to https - angularjs

I'm using the mean stack (angular v1.4.7, node v0.12.7, express 4.9.0) for my project.
Recently, i adquire ssl certificates and install them on the server, so i had to change my http requests to https.
I also change the nodejs server to requires https instead of the http, but the express routes stopped working and every request is returning net::ERR_CONNECTION_CLOSED. Here is some examples:
Request on angularjs:
$http({
url: "https://www.urbs.pt:3000/auth/isauth",
method: "GET",
withCredentials: true
}).success(function (data, status, headers, config) {
$scope.isloggedin = data;
}).error(function (data, status, headers, config) {
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
});
I'm running my nodejs server with express on port 3000 using https
var authenticate = require('./routes/authenticate');
var options = {
key: fs.readFileSync(pathtokey),
cert: fs.readFileSync(pathtocertificate),
ca: fs.readFileSync(pathtoCA),
requestCert: true,
rejectUnauthorized: false
};
var app = express();
var https = require('https').Server(options,app);
/* this part is initialized on bin/www
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
*/
app.use('/auth', authenticate);
If i use http protocol on the angularjs request, and require http on nodejs everything is working as expected, so i guess that the problem is with the https request. I also confirmed that the options configurations are correct.

Related

Express/Angular/Browsersync CORS - No 'Access-Control-Allow-Origin' 403 (forbidden)

I'm as junior as it gets when it comes to web development so please bear with me on this. I'm attempting to access data from the USDA Food Composition Databases NDB API - https://ndb.nal.usda.gov/ndb/doc/index
via an angular $http request from localhost. I'm using an express server and gulp/browsersync and am encountering two errors:
Failed to load resource: http://api.nal.usda.gov/ndb/list?format=json&It=f&max=20&sort=n&offset=15&api_key=API_KEY the server responded with a status of
and
XMLHttpRequest cannot load http://api.nal.usda.gov/ndb/list?format=json&It=f&max=20&sort=n&offset=15&api_key=API_KEY. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 403.
I've tried setting my CORS headers in browsersync as well as my express server but I simply cannot get around this issue. Here is how I've configured the relevant code for this:
The $http request
(function() {
'use strict';
angular
.module('commonSenseDietApp')
.factory('getFoodNamesOnly', getFoodNamesOnly);
/** #ngInject */
function getFoodNamesOnly($log, $http, devEnvironment) {
var service = {
ndbApiKey: devEnvironment.api_key,
ndbApiUrl: devEnvironment.api_url,
getFoodNamesList: getFoodNamesList
};
return service;
function getFoodNamesList(limit) {
if(!limit) {
limit = 30;
}
// For a list of all request parameters visit - https://ndb.nal.usda.gov/ndb/doc/apilist/API-LIST.md
return $http.get(service.ndbApiUrl + '/ndb/list?format=json&It=f' + '&max=' + limit + '&sort=n&offset=15&api_key=' + service.ndbApiKey)
.then(returnFoodNamesList)
.catch(getFoodNamesFail);
function returnFoodNamesList(response) {
return response.data;
}
function getFoodNamesFail(err) {
// return $log.error(err.data);
return console.log(err);
}
}
}
})();
My Browersync/Express Server
'use strict';
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var http = require('http')
// require database data modeling via mongoose
var mongoose = require('mongoose');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
// Use express and set it up
var app = express();
app.use(cors());
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', false);
next();
});
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json())
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
function browserSyncInit(baseDir, browser) {
browser = browser === undefined ? 'default' : browser;
var routes = null;
if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
routes = {
'/bower_components': 'bower_components'
};
}
var server = {
baseDir: baseDir,
routes: routes,
middleware: 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');
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', false);
next();
}
};
browserSync.instance = browserSync.init({
startPath: '/',
cors: true,
browser: browser,
notify: true,
port: 8080,
server: server,
});
}
browserSync.use(browserSyncSpa({
selector: '[ng-app]'// Only needed for angular apps
}));
gulp.task('serve', ['setenvconstants','watch'], function () {
browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.src]);
});
gulp.task('serve:dist', ['setenvconstants','build'], function () {
browserSyncInit(conf.paths.dist);
});
gulp.task('serve:e2e', ['inject'], function () {
browserSyncInit([conf.paths.tmp + '/serve', conf.paths.src], []);
});
gulp.task('serve:e2e-dist', ['build'], function () {
browserSyncInit(conf.paths.dist, []);
});
My Angular .config
(function() {
'use strict';
angular
.module('commonSenseDietApp')
.config(config);
/** #ngInject */
function config($logProvider, $httpProvider) {
// Enable log
$logProvider.debugEnabled(true);
// For Access-Control-Allow-Origin and Set-Cookie header
$httpProvider.defaults.withCredentials = false;
}
})();
I'm using gulp and browsersync to serve locally over localhost:8080 but no matter what I try (setting headers in express, setting headers in browsersync, setting browsersync cors option to 'true', setting browsersync https options to true, switching my 'Access-Control-Allow-Origin' to '*' or to "localhost:8080") none of it seems to work. I suspect the NDB API has forbidden my access but I can't get in contact with them to ask about it. Their suggested contact us link - "https://api.data.gov/contact/" leads to nothing.
Any suggestions or tips on this would be greatly appreciated. I'm a total noob here in terms of web development as well as posting to Stack Overflow so please let me know if my question doesn't make any sense and needs further clarification.
I was fortunate enough to stumble upon a solution although I don't quite understand what's happening and would certainly like to.
Turns out I was attempting to run a local server while using my VPN (https://www.privateinternetaccess.com/) which for some reasons was causing my CORS issue. Once I turned the VPN off and began using my local network I was able to run my server and make my requests without a hitch.
I'm not sure why using my VPN would cause a 403 but my guess would be that the API I was attempting to access simply does not allow request from a remote network like the one I was using. I will look into it more and update my answer shortly.
Try serving from https and not http when making your API calls. Being that you are fetching an https location, but issuing an http request, you will get CORS issue.
Look into: https://nodejs.org/api/https.html

Session undefined in Express when AngularJS as frontend

I have written webservice using NodeJS and Express. Service is running on port 8090. Also I wrote frontend in AngularJS and running on port 8080.
Mongo has username and password stored of all users
When I login via HTML5/AngularJS frontend, the AngularJS app in turn calls the http post request of express. User is authenticated. And I set req.session.email = the email address of the user.
I even am able to return and check in console log of AngularJS that req.session.email was set correct in express
The problem is that I created an authentication function called "restrict" in Express to act as middleware function to give access to other get/post requests only if req.session.email is not undefined.
But even after session has been set, when this other get/post request of Express are calling by AngularJS app, this "restrict" function blocks the calls because it receives req.session.email as undefined
Both AngularJS and Express are on the same machine. But I don't think this is the problem.
Express Code Snippet
var url = 'mongodb://127.0.0.1:5555/contacts?maxPoolSize=2';
var mongojs = require('mongojs');
var db = mongojs(url,['data']);
var dbauth = mongojs(url,['users']);
// var request = require('request');
var http = require('http');
var express = require('express');
var cookieparser = require('cookie-parser');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
app.use(cookieparser());
app.use(session({secret:'v3ryc0mpl!c#t3dk3y', resave: false, saveUninitialized: true}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var user_session;
app.all('*',function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
function restrict(req,res,next){
try{
if(req.session.email){
next();
}
else{
res.send('failed');
res.end();
}
}
catch(err){
res.send('failed');
res.end();
}
};
app.post('/login',function(req,res){
//removed DB function from here to make the code look simple
req.session.email = req.body.email;
req.session.password = req.body.password;
});
app.get('/loggedin',restrict,function(req,res){
res.send(true);
});
AngularJS Function that calls the Express function to check session status
var resolveFactory = function ($q, $http, $location,LoginDetails) {
var deferred = $q.defer();
$http.get("http://127.0.0.1:8090/loggedin")
.success(function (response) {
if(response == true){
deferred.resolve(true);
}
else
{
deferred.reject();
LoginDetails.setemail('');
LoginDetails.setpassword('');
$location.path("/");
}
})
.error(function (err) {
deferred.reject();
$location.path("/");
});
return deferred.promise;
};
Fundamentally the AngularJS Resolve Function that I created should be successful but it is not. It is failing. Am using live-server to run HTML/AngularJS on my laptop and nodemon to run Express app
Ok! So the reason is that AngularJS is running on a different port 8080
Express was running on port 8090. This means that if AngularJS calls an API of Express, the session of Express would be lost unless Express allows session to be passed on to AngularJS and AngularJS calls the API of Express with {withCredentials: true} parameter set. Below are the changes that I had to make to get the session maintained when AngularJS and ExpressJS were running on different ports
In AngularJS makes sure any API you call of Express, it should have
{withCredentials: true} like this
$http.get('http://expressdomainname:expressport/api',{withCredentials: true})
like wise in case you use $http.post
the parameter {withCredentials: true} is important
Now on the Express side
make sure you have app setting like this
app.all('*',function(req, res, next){
//Origin is the HTML/AngularJS domain from where the ExpressJS API would be called
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
//make sure you set this parameter and make it true so that AngularJS and Express are able to exchange session values between each other
res.header("Access-Control-Allow-Credentials", "true");
next();
});
Please feel free to ask me question in case you have about this topic. I spent days to resolve this.

enabling cors in meanjs rest api server

I am creating an api (server side) based on Meanjs.org latest version (0.4.0) and i managed to pull off only the MEN part and create one in http://localhost:3000/api
as the frontend part i created an Angularjs in http://localhost:4000/
and then i run both application using (P)ackage (M)anager 2
I am trying to create a user by sending user credentials using $resource like this
angular.module('users').factory('AuthenticationResource', ['$resource',
function($resource) {
return $resource('http://localhost:3000/api/auth/signup', {}, {
post: {
method: 'POST'
}
});
}
]);
...
//In my controller
$scope.signup = function() {
AuthenticationResource.post($scope.credentials, function(response) {
$scope.authentication.user = response;
$state.go($state.previous.state.name || 'home', $state.previous.params);
});
};
While in my server side's express.js
'use strict';
var config = require('../config'),
express = require('express'),
...
cors = require('cors');
...
module.exports.initModulesServerRoutes = function(app) {
// Globbing routing files
config.files.server.routes.forEach(function(routePath) {
require(path.resolve(routePath))(app);
});
};
module.exports.initCorsOption = function(app){
app.options('*', cors());
};
module.exports.init = function(db) {
// Initialize express app
var app = express();
...
// Initialise Cors options
this.initCorsOption(app);
// Initialize modules server routes
this.initModulesServerRoutes(app);
...
return app;
};
I am using node cors package to enable cors and just do app.options('*', cors()); to enable pre-flight across-the-board
But when i am trying to do a POST to http://localhost:3000/api/auth/signup i can see that my user is being saved to the database just fine but it doesn't give me any response and chrome console is giving me this
XMLHttpRequest cannot load http://localhost:3000/api/auth/signup. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access.
What did i miss?
I think you are missing app.use before all your routes:
Only express:
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");
next();
});
If you are using npm cors:
app.use(cors());

CORS issue with node rest api and angularJS app on 2 ports

I have the classical CORS issue with my angularJS app (on localhost:9000) trying to catch my node server (on localhost:9001)
Here my rest api (app.js) code :
var cors = require('cors');
app.use(cors());
app.options('*', cors());
app.all('/*', function(req, res, next) {
// CORS headers
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
if (req.method == 'OPTIONS') {
res.status(200);
res.write("Allow: GET,PUT,POST,DELETE,OPTIONS");
res.end();
} else {
next();
}
});
As you can see, i've tried those solutions in vain :
CORS in Node.js and AngularJS
Cors issue when rest api application server(express) and Angulars js application running on different port
And here's the simple $http call in webapp :
var req = {
method: 'GET',
url: 'localhost:9001/memories'
};
$http(req).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
reutrnStatus.success = true;
reutrnStatus.msg = status;
memories = data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
reutrnStatus.success = false;
reutrnStatus.msg = status;
});
I tried some solutions in webapp too (in app.js) :
// Enable AngularJS to send its requests with the appropriate CORS headers
// globally for the whole app:
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
/**
* Just setting useXDomain to true is not enough. AJAX request are also
* send with the X-Requested-With header, which indicate them as being
* AJAX. Removing the header is necessary, so the server is not
* rejecting the incoming request.
**/
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
But i'm close to give up because it's still not working... That's giving me this same error :
XMLHttpRequest cannot load localhost:9001/memories. Cross origin
requests are only supported for protocol schemes: http, data, chrome,
chrome-extension, https, chrome-extension-resource.
And just to be fully clear, i followed that tutorial for the rest api :
https://blog.jixee.me/how-to-write-an-api-in-one-week-part-2/
You are making a request to an unknown protocol.
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
You need to change this:
method: 'GET',
url: 'localhost:9001/memories'
};
...to this:
method: 'GET',
url: 'http://localhost:9001/memories'
};
Alternatively, you could set it to //localhost:9001/memories and the browser will use the current protocol which is useful if you're serving resources over both http and https.
Although unrelated, your callbacks have typos in the variable names.

Can't access to POST parameters using expressJs with AngularJs POST Request

I can't access to my post parameters when I'm doing post request with angular, here is my angular code :
var request = $http({
method: 'POST',
url: '/api/login',
data: {
login: 'alex',
password: 'test'
}
})
.success(function (res, status, headers) {
if (res.token != 'undefined'){
user.token = res.token;
user.login = credentials.login;
user.userid = res.userid;
user.islogged = true;
$cookieStore.put("user", user);
}
}).error(function(data, status, headers, config) {
console.log(data);
});
Here is my back-end code in my router file :
/************ API ******************/
app.post('/api/login', user.login);
And here is the code of my user controller
exports.login = function(req, res) {
console.log(req);
var user = {
login: req.query.login,
password: sha1(req.query.password)
};
...
}
I have nothing in req.query object otherwise if I make my request with Advanced REST Client plugin for chrome everything work fine.
Note: I'm using body-parser module to read parameters of my request.
Here is the github repository : https://github.com/alex3165/numeractive/tree/dev/node
Make sure you enables the use of json parser
var bodyParser = require("body-parser");
app.use(bodyParser.json());
Note: you have to install body-parser package, just open your terminal (command prompt in windows), chnage your directory to the root of your project and type the following
$ npm install body-parser --save

Resources