Creating an HTTPs server with Node.js and Express - javascript

var https = require('https'),
fs = require('fs'),
express = require('express'),
app = express();
// cookieParser = require('cookie-parser'),
// path = require('path'),
// bodyParser = require('body-parser'),
// https = require('http');
var key = fs.readFileSync('encryption/star_massifsolutions_com.key');
var cert = fs.readFileSync('encryption/massif_wildcard.crt');
var ca = fs.readFileSync('encryption/DigiCertCA.crt');
var httpsOptions = {
key: key,
cert: cert,
ca: ca
};
https.createServer(httpsOptions, app).listen(8000, function () {
console.log("server running at https://IP_ADDRESS:8000/")
});
app.get('/', function (req, res) {
res.header('Content-type', 'text/html');
return res.end('Hello World!');
});
// app.set('view', __dirname + '/views');
// app.use(bodyParser.urlencoded({
// extended: true
// }));
// app.use(bodyParser.json({
// limit: '500mb'
// }));
// app.use('/', express.static(path.join(__dirname, '/dist/basic-structure')));
// app.get('/**', function (req, res, next) {
// console.log(req, res, next);
// res.sendFile('index.html', {
// root: __dirname + '/dist/basic-structure'
// });
// });
console.log("listening to port 8000");
Here i have written hello world just to test my code.so in this case code runs but its not secure. I want my connection to be secure.In this case it shows deprecated http and shows certificate error.but and run unsecurly.
Again if I replace the hello world part with the commented part as shown in my code it doesn't even run with the deprecated http.if i replace the https with http it runs. I want help in running my edited code. If i am missing some points please let me know.
In short this code is running insecurly , i want to make it secure

Not sure if I understand well, but if by "the code is not running" you mean your app, then it seems your 2nd code set simply try to run a server but not your app
To my understanding, you are defining your app as express but you are not using it, so it will not be delivered
So my guess is that you will need to use the https server command with the app and its options to link everything together (https and app) as suggested by #lx1412
I would try this :
var express = require('express'),
cookieParser = require('cookie-parser'),
path = require('path'),
bodyParser = require('body-parser'),
// https = require('http'),
https = require('https'),
app = express(),
fs = require('fs');
var key = fs.readFileSync('encryption/star_massifsolutions_com.key');
var cert = fs.readFileSync( 'encryption/massif_wildcard.crt' );
var ca = fs.readFileSync( 'encryption/DigiCertCA.crt' );
var httpsOptions = {
key: key,
cert: cert,
ca: ca
};
app.set('view',__dirname+'/views');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json({limit: '500mb'}));
app.use('/', express.static(path.join(__dirname,'/dist/basic-structure')));
app.get('/**', function(req, res, next) {
console.log(req, res, next);
res.sendFile('index.html', { root: __dirname +
'/dist/basic-structure' });
});
// https.createServer(httpsOptions, (req, res) => {
// console.log("code works");
// res.writeHead(200);
// res.end('hello world\n');
// }).listen(8000);
https.createServer(httpsOptions, app).listen(8000, function () {
console.log("code works");
res.writeHead(200);
res.end('hello world\n');
});
EDIT :
Can you simply try this and see how it behaves ?
Also, can you provide your deprecated http and certificate error ?
app.get('/', function (req, res) {
res.send('Hello World!');
});
https.createServer(httpsOptions, app).listen(8000, function () {
console.log("server running at https://IP_ADDRESS:8000/")
});

It's simple.
var express = require('express'),
cookieParser = require('cookie-parser'),
path = require('path'),
bodyParser = require('body-parser'),
http = require('http'),
app = express();
app.set('view',__dirname+'/views');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json({limit: '500mb'}));
app.use('/', express.static(path.join(__dirname,'/dist/basic-structure')));
app.get('/**', function(req, res, next) {
console.log(req, res, next);
res.sendFile('index.html', { root: __dirname +
'/dist/basic-structure' });
});
//Start Server
//app.listen(3004, function(){
// console.log('>>>3004')
//});
//complete your code here
https.createServer(httpsOptions,app).listen(8000);

Related

Express: Serving static files for defined routes

When I visit mysite.com/verify/myusn the result is a 404 error. When I visit mysite.com/ it serves me the index page as expected.
When I turned on the debugger, I realized Express was trying to serve a static file instead. But it also shows my route being registered properly. Please help me out.
Here is my debugger:
Here is my server.js:
var express = require('express');
var app = express();
var path = require('path');
app.get('/*', function(req, res, next){
next();
});
app.use(express.static(path.join(__dirname , '/_site/') , {maxAge:0}));
app.use('/assets/', express.static(path.join(__dirname , '/_site/assets') , {maxAge:0}));
var routesLogin = require(path.join(__dirname, '/api/routes/users'));
routesLogin(app);
app.get('/', function(req, res) {
res.sendFile( path.join(__dirname , '/_site/landing.html'));
});
app.get('*', function(req, res) {
res.send('404');
});
app.post('*', function(req, res) {
res.send('404');
});
port = process.env.PORT || 3000;
app.listen(port);
console.log('listening on ' + port);
./api/routes/users.js:
module.exports = function(app){
var users = require('../controllers/userController');
app.route('verify/:usn')
.get(users.verifyUSN)
};
./api/controllers/userController.js:
exports.verifyUSN = function(req, res, next){
res.status(200)
.json({
status: 'success',
data: data,
message: 'USN Verified.'
});
}
I believe your problem could potentially be in /api/routes/users.js
module.exports = function(app){
var users = require('../controllers/userController');
// previously app.route('verify/:usn')
app.route('/verify/:usn')
.get(users.verifyUSN)
};
Hope this helps.

Calling node api through postman with response as enable javascript error

When calling API https://mywebsite.com/api/register through browser and it returns correct response from server as { "error": false, "message": "Hello World" }
If we hit the same request from postman then it returns with some html content as Please enable JavaScript to view the page content.
Below is node side code:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ limit: '50mb', "extended": false }));
router.get("/", function (req, res) {
res.json({ "error": false, "message": "Hello World" });
});
The api working through the browser but not with postman. What will be the possible errors?
If you want to separate the router files then use the following pattern otherwise use app.get()
app.js
var express = require('express'),
car = require('./routes/car'),
bus = require('./routes/bus');
var app = express();
app.use('/car', car);
app.use('/bus', bus);
app.listen(2000);
car.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('GET handler for /car route.');
});
router.post('/', function(req, res) {
res.send('POST handler for /car route.');
});
router.put('/', function(req, res) {
res.send('put handler for /car route.');
});
module.exports = router;
Try this instead:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ limit: '50mb', "extended": false }));
app.listen(8080);
app.get("/", function (req, res) {
res.json({ "error": false, "message": "Hello World" });
});
Replace router.get with app.get.
I test your code on my browser and it doesn't work too.

Express routing error Cannot Get /api/name

Having some trouble setting up the restful API for my express app.
Here is my app.js:
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override');
routes = require('./routes'),
api = require('./routes/api'),
port = process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(bodyParser.urlencoded({extended: true}));
// Page Routes
app.get('/', routes.index);
app.get('/partials/:filename', routes.partials);
// // API Routes
app.get('/api/name', api.name);
app.listen(port, function() {
console.log('Listening on port ' + port);
});
In /routes/api.js I have the following test function:
exports.name = function (req, res) {
res.json({
name: 'Test'
});
};
Currently I get the following error when i go to http://my_ip/api/name
Cannot GET /api/name
Any ideas?
Thanks
The following code is working for me. I think there is some issue with your routes package. Can you share the code of 'routes' package and file structure ?
app.js
var express = require('express'),
app = express(),
routes = require('./routes');
api = require('./routes/api'),
port = process.env.PORT || 3000;
// Page Routes
app.get('/', routes.index);
// API Routes
app.get('/api/name', api.name);
app.listen(port, function() {
console.log('Listening on port ' + port);
});
/routes/api.js
exports.name = function (req, res) {
res.json({
name: 'Test'
});
};
/routes.js
exports.index = function (req, res) {
res.json({
name: 'Index'
});
};

How to get my node.js mocha test running?

I have developed a service in node.js and looking to create my first ever mocha test for this in a seperate file test.js, so I can run the test like this:
mocha test
I could not figure out how to get the reference to my app, routes.js:
var _ = require('underscore');
module.exports = function (app) {
app.post('/*', function (req, res) {
var schema={
type: Object,
"schema":
{
"totalRecords": {type:Number}
}
};
var isvalid = require('isvalid');
var validJson=true;
isvalid(req.body,schema
, function(err, validObj) {
if (!validObj) {
validJson = false;
}
handleRequest(validJson,res,err,req);
});
})
}
This is the server.js:
// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var port = process.env.PORT || 8080; // set the port
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use (function (error, req, res, next){
res.setHeader('content-type', 'application/json');
res.status(400);
res.json({
"error": "errormsg"
});
});
// routes ======================================================================
require('./routes.js')(app);
// listen (start app with node server.js) ======================================
app.listen(port);
console.log("App listening on port " + port);
And finally test.js:
"use strict";
var request = require('supertest');
var assert = require('assert');
var express = require('express');
var app = express();
describe('testing filter', function() {
it('should return an error', function (done) {
request(app)
.post('/')
.send({"hh":"ss"})
.expect(400,{"error": "errormsg"})
.end(function (err, res) {
if (err) {
done(err);
} else {
done();
}
});
});
});
Create a separate file called app.js. The only purpose of this file would be to run the server. You'll also need to export your app object from server.js. So, your server.js would look like this
// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var port = process.env.PORT || 8080; // set the port
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use (function (error, req, res, next){
res.setHeader('content-type', 'application/json');
res.status(400);
res.json({
"error": "errormsg"
});
});
// routes ======================================================================
require('./routes.js')(app);
module.exports = app;
Create a new file called app.js and put this inside of it
var app = require('./app');
var port = process.env.port || 8000;
app.listen(port, function() {
console.log("App listening on port " + port);
});
Now, inside of your test file, import your app as follows
var request = require('supertest');
var assert = require('assert');
var app = require('./app.js');
....
Note that I assume all your files are in the same directory. If you've put your test file in a different folder then you'll need to give the right path while requiring your app object.

router.get('/') on expressjs not working

i can't access to my express application's home page by '/' route pattern. it's working on /index e.g. My express version is 4.6.
I tried app.use('/*', router), but my application is not responding or 503 service temporarily unavailable. It's now working by '/index' pattern and other routes is working correctly. only '/' pattern is not working. :)
Here is my code snippet.
var http = require('http');
var express = require('express');
var app = express();
var router = express.Router();
app.use('/', router);
app.set('view engine', 'ejs');
app.set('views', './views');
app.use(express.static('./public'));
var bodyParser = require("body-parser");
app.use(bodyParser());
var fs = require('fs');
var clientSessions = require("client-sessions");
var form = require('express-form');
var field = form.field;
var sha1 = require('sha1');
var mysql = require('mysql');
var connection = mysql.createConnection({
host: process.env.OPENSHIFT_MYSQL_DB_HOST,
port: process.env.OPENSHIFT_MYSQL_DB_PORT,
user: process.env.OPENSHIFT_MYSQL_DB_USERNAME,
password: process.env.OPENSHIFT_MYSQL_DB_PASSWORD,
database: process.env.OPENSHIFT_GEAR_NAME
});
var multer = require('multer');
var done = false;
app.use(clientSessions({
secret: 'xxxxx'
}));
app.use(function(req, res) {
res.status(400);
res.render('pages/404');
});
// Handle 500
app.use(function(error, req, res, next) {
res.status(500);
res.render('pages/500');
});
//---
app.use(multer({
dest: 'public/uploads/',
rename: function(fieldname, filename) {
return filename + Date.now();
},
onFileUploadStart: function(file) {
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function(file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
done = true;
}
}));
//// --------------- start app routes --------------//
// ----- GET -----
router.get('/', function() { // THIS PATTERN IS NOT WORKING
console.log('hello world'); // this line is not working
connection.query(strQuery, function(err, rows) {
// res.render('pages/index');
});
});
Because you didn't handle "/", here is updated code
var router = express.Router();
app.use('/*', router);
router.get('/', function(req, res) {
res.send('welcome home');
}
router.get('/index', function(req, res) {
res.send('welcome index');
}
You are forgetting '*' in second line
app.use('/*', router);
Do you forget to make redirection?
router.get("/", function (req, res) {
res.redirect("/index");
});

Categories