Node.js and Express relationship - javascript

I'm trying to understand the connection between Node.js and Express.
My Code for creating a Node.js Server:
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('./https1/key.pem'),
cert: fs.readFileSync('./https1/cert.pem')
};
const server = https.createServer(options, function(req,res){
res.writeHead(200);
res.end(`Hello world!!!!!!!!!!! \n`);
});
server.listen(3000, function(){
console.log('Server listening on port 3000 \n');
});
I run a curl operation curl -k localhost:3000 and it gives me a "Hello World" Output
My code for creating an Express Server:
// call the packages we need
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
// ROUTES FOR OUR API
var router = express.Router();
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.listen(port);
console.log('Magic happens on port ' + port);
Is it possible for us to mix both of these?
To be more specific, I would like to create my Server using the Node.js way, but create my routes using the Express way. Can I do it or should I just follow one methodology? What is the connection between Node.js and Express? I understand that Express is just a framework for Node.js but where exactly does the deviation occurs if at all any?
Can I mix and combine the two when required?
Thank you

Yes you can combine nodejs and express, but not encourage you to combine those unless you have specific purpose such as using AWS lambda or making specific OS tasks that has to be made only with pure node.
As you already know, express is just a framework. You can write code more shortly using express.
For example, to make the browser displaying Hello world,
// nodejs version
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// express version
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, (req, res) => {
res.send('Hello World!\n');
})
More easier, and intuitive.

You surely can that's the way to create a Secure HTTPS server with express and followed in most projects
const https = require('https');
const express = require('express');
const app = express();
const options = {
key: fs.readFileSync('./https1/key.pem'),
cert: fs.readFileSync('./https1/cert.pem')
};
const server = https.createServer(options, app);
app.get('/', (req, res) => {
res.send('hello world')
}
server.listen(config.port, () => {
console.log(`Express server listening on port ${port} in ${app.get('env')} mode`);
});
Now add your routes and all.

Related

Website still shows up when I shut down the server in AWS, Nodejs Express

I'm using React-ecommerce, nodejs and express. I'm using an EC2-Instance on AWS. So, when I go to ghostnft.tech, it says "Hello World", when my server is working. Even if the server is running on port 8080 and I don't open ghostnft.tech:8080. I don't know why this is happening but it works, so it's good. The problem is, when I shut down the server, it still says "Hello World" on the website. How can that be? And even now after two days the server is shut down, it still works. And when I update the server so it should say "Hello World!", it doesn't update on the website. Plus, when I first started the server and connected everything on AWS, when I go to the public IPv4-DNS address, but then with "ec2-2.32.example.aws.amazon.com:8080", it gave me from 2 out of 3 refreshes a "502 Bad Gateway". On ghostnft.tech it gave me everytime the 502. Then, after about 3 hours there wasn't any 502 on ghostnft.tech and it worked. What happened here?
Below you see my index.js, that is like the server.js.
const express = require('express');
const cors = require('cors');
require('dotenv').config({ path: './.env' });
const createCheckoutSession = require('./api//checkout');
const webhook = require('./api/webhook');
const app = express();
const port = 8080;
const server = app.listen(port, () => console.log('server listening on port', port));
server.keepAliveTimeout = 65000;
server.headersTimeout = 70000;
app.use(express.json({
verify: (req, res, buffer) => req['rawBody'] = buffer,
}));
app.use(cors({ origin: true }));
app.use(cors(corsOptions)) // Use this after the variable declaration
app.get('/', (req, res) => res.send('Hello World!!!'));
app.post('/create-checkout-session', createCheckoutSession);
app.post('/webhook', webhook);
And because of the 502 I tried this, but the website won't update:
const express = require('express');
const cors = require('cors');
require('dotenv').config({ path: './.env' });
const createCheckoutSession = require('./api//checkout');
const webhook = require('./api/webhook');
const app = express();
const port = 8080;
const server = app.listen(port, () => console.log('server listening on port', port));
server.keepAliveTimeout = 65000;
server.headersTimeout = 70000;
app.use(express.json({
verify: (req, res, buffer) => req['rawBody'] = buffer,
}));
const corsOptions = {
origin:'*',
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200,
}
app.use(cors(corsOptions)) // Use this after the variable declaration
app.get('/', (req, res) => res.send('Hello World!!!'));
app.post('/create-checkout-session', createCheckoutSession);
app.post('/webhook', webhook);

How to start expressjs on shared A2hosting?

I have search a lot and I can't seem to start express js app. All I'm getting is 404 error.
Default app.js file which has http server and it works fine.
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var message = 'It works!\n',
version = 'NodeJS ' + process.versions.node + '\n',
response = [message, version].join('\n');
res.end(response);
});
server.listen();
And this is express js code which is not working. giving me 404 error.
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
server.listen();
I also tried few other combination as well.
var express = require('express');
var app = express();
app.get('/', (req, res) => res.send('Hello World!'));
var http = require('http');
var server = http.createServer(app);
server.listen();
this one also didn't work
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => res.send('Hello World!'));
server.listen();
I also tried expressjs to create it own server and it also didn't work.
const express = require('express');
const app = express();
const port = 80;
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
I also tried to remove port from app listen and not surprisingly it also didn't work.
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello World!'));
app.listen();
I also tried everything from express-js-app-listen-vs-server-listen page but not successful.
This is the error I get
For others with the same A2 Hosting issue, the solution is actually so easy...
The problem with the application running the NodeJS deployment on cPanel. Phusion Passenger does not use the root path as '/', but as '/yourAppURL'. So in your NodeJS code, you have to add the specified AppURLPath to the call when using Express...
e.g.
//Instead of
app.get('/', (req, res) => res.send('Hello World!'));
//Change to
app.get('/YourSpesifiedAppURLPath/', (req, res) => res.send('Hello World!'));

Get method not able to be detected by the Node.js

I am new to node and express js.Today I am learning and I have initialized node server as:
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const PORT = 3000
const api=require('./routes/api')
const app = express()
app.use(bodyParser.json())
app.use(cors())
api.use('/api',api)
app.get('/', function(req, res) {
res.send('Hello from server')
})
app.listen(PORT, function(){
console.log("Server running on localhost:" + PORT)
});
I have created a folder routes inside server folder and there is api.js file which has GET method to test, whether the api is working or not.Inside api.js I have,
const express = require('express')
const router=express.Router()
router.get('/', (req, res) => {
res.send('from Api Route');
})
module.exports=router
I type node server and it is displaying me :
Server running on localhost:3000
But,when I try to get the url: http://localhost:3000/api,it is displaying me:
And,in api.js file in the arrow function sublime is showing me error in red marker as:
Replace api.use('/api',api) with app.use('/api',api)

Express Post Request 404

I'll try to make this as to the point as possible. I am trying to make a post request to my express backend. All of the post requests here work, except for "/addpayment". Here is my file called 'router.js'
module.exports = function(app) {
app.post('/signin', requireSignin, Authentication.signin)
app.post('/signup', Authentication.signup)
app.post('/addpayment', function(req, res, next) {
res.send({ message: 'why................' })
})
}
Here is my main 'server.js' file
const express = require('express')
const http = require('http')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const app = express()
const router = require('./router')
const mongoose = require('mongoose')
const cors = require('cors')
// DB Connect
mongoose.connect('mongodb://localhost/demo-app')
// App
app.use(morgan('combined'))
app.use(cors())
app.use(bodyParser.json({ type: '*/*' }))
router(app)
// Server
const port = process.env.PORT || 3090
const server = http.createServer(app)
server.listen(port)
console.log('Server has been started, and is listening on port: ' + port)
I get a 404 in postman, and inside my app browser console. I am using passport in my other routes. I already tried running it through passport when I have a JWT token, and same thing(a 404).
I have already looked at all Stack Overflow/Github posts on the first few pages of google results, with no solution for my use case.
I have made a simplified version of your server and everything works as expected. Only difference that I have made is that I am not creating http server like you, but just calling app.listen
here is working example
router.js
module.exports = function(app) {
app.post('/addpayment', function(req, res, next) {
res.send({message: 'why................'})
})
};
server.js
var express = require('express');
var router = require('./router');
var app = express();
router(app);
//init server
app.listen(3000, function() {
console.log("Server running on port 3000");
});

Listen on HTTP and HTTPS for a single express app

Can I create an Express server listening on both HTTP and HTTPS, with the same routes and the same middlewares?
Currently I do this with Express on HTTP, with stunnel tunneling HTTPS to Express, but I prefer a pure Node solution.
I can do it with this code, but using the handle method that is marked as private:
var express = require( 'express' )
, https = require("https")
, fs = require( 'fs' );
var app = express.createServer();
// init routes and middlewares
app.listen( 80 );
var privateKey = fs.readFileSync( 'privatekey.pem' ).toString();
var certificate = fs.readFileSync( 'certificate.pem' ).toString();
var options = {key: privateKey, cert: certificate};
https.createServer( options, function(req,res)
{
app.handle( req, res );
} ).listen( 443 );
To enable your app to listen for both http and https on ports 80 and 443 respectively, do the following
Create an express app:
var express = require('express');
var app = express();
The app returned by express() is a JavaScript function. It can be be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app using the same code base.
You can do so as follows:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {
key: fs.readFileSync('/path/to/key.pem'),
cert: fs.readFileSync('/path/to/cert.pem'),
ca: fs.readFileSync('/path/to/ca.pem')
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
For complete detail see the doc
As a possible update to this question, you might want to check out the changes here for express 3. The change document says:
The return value of express() is a JavaScript Function,
encapsulating everything that makes an Express app tick. This means
you can easily setup HTTP and HTTPS versions of your application by
passing it to node's http.createServer() and https.createServer():
In Express 3, express.createServer() is now express()
Here is a complete example for express 3:
var fs = require('fs')
, https = require('https')
, http = require('http')
, express = require('express')
, keys_dir = 'keys/'
, server_options = {
key : fs.readFileSync(keys_dir + 'privatekey.pem'),
ca : fs.readFileSync(keys_dir + 'certauthority.pem'),
cert : fs.readFileSync(keys_dir + 'certificate.pem')
}
, app = express();
app.configure(function(){
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session( { secret: '' } ));
app.use(app.router);
});
app.configure('development',function(){
app.use(express.static(__dirname + '/public'));
app.use(express.errorHandler({dumpExceptions: true, showStack:true}));
app.set('view options', { pretty: true });
});
app.get('/', function(req, res){
res.send('Hello World!');
});
https.createServer(server_options,app).listen(7000);
http.createServer(app).listen(8000);
You can share the implementation via something like:
var register = function (app) {
// config middleware
app.configure({
});
// config routes
app.get(...);
};
var http = express.createServer();
register(http);
http.listen(80);
var https = express.createServer({ key: /* https properties */ });
register(https);
https.listen(443);
You can use express and https in same port.
this works for me.
const express=require('express');
const app=express();
const cors=require('cors');
const path=require("path");
const routes=require('./routes/api');
const routerComplain=require('./routes/api');
const routerstores=require('./routes/api');
const routerstock=require('./routes/api');
const routerreport=require('./routes/api');
const routeritem=require('./routes/api');
const bodyParser=require('body-parser');
const routerRegister=require('./routes/api');
const mongoose=require('mongoose');
var server = require('http').Server(app);
var io = require('socket.io')(server);
require("dotenv").config();
mongoose.connect('mongodb://#################',{ useNewUrlParser: true },(err)=>{
if(!err){
console.log('db connected')
}else{
console.log('error in db')
}
});
mongoose.Promise = global.Promise;
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(cors({credentials: true, origin:'http://localhost:3000'}));
app.use(express.static(path.join(__dirname, "client", "build")))
app.use('/reg',routes);
app.use('/complain',routerComplain);
app.use('/register',routerRegister);
app.use('/stores',routerstores);
app.use('/reports',routerreport);
app.use('/stock',routerstock);
app.use('/items',routeritem);
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
})
const port = process.env.port||4000;
server.listen(port,function(){
console.log('now listening for request');
});
If you want to use the traditional two ports, one of the above solutions probably works, but using httpolyglot, you can really easily have http and https on the same port with the same middlewares.
https://github.com/mscdex/httpolyglot
Here's some skeleton code that worked for me:
var express = require('express');
var fs = require('fs');
var httpolyglot = require('httpolyglot');
var app = express();
const options = {
key: fs.readFileSync("/etc/ssl/certs/key"),
cert: fs.readFileSync("/etc/ssl/certs/cer.cer")
};
httpolyglot.createServer(options, app).listen(port);
and if you want http -> https forwarding, you can just add this middleware function before the createServer() call:
app.use(function(req, res, next) {
if (!req.secure ) {
res.redirect (301, 'https://' + req.hostname + ':port' + req.originalUrl);
}
next();
});
This can be set up on a custom port
Similar post
Can I configure expressjs to serve some pages over http and others over https?
Be aware that express now support creating Https servers with:
var app = require('express').createServer({ key: ... });

Categories

Resources