I just want a simple http server to control GET and POST request.
I made one using nodejs and express. It works great at localhost. But it's not possible to connect this server remotely.
I also set static ip address and port forwarding but it's still not possible.
I tried port number 80 and 9000 both are set port forwarding.
Can any one help me?
var http = require("http");
var express = require("express");
var app = express();
var port = 80;
app.get('/', function (req,res) {
console.log('app.get');
res.send('abc');
});
app.post('/test', function(req,res) {
console.log('app.post');
});
http.createServer(app).listen(port,function () {
console.log('createServer');
});
Related
I've just started learning node.js but when I try to launch the hello world code by writing on the terminal node server.js, localhost:3000 gives me the following error:
This page isn’t working;
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
I've been searching for 2h now and I've found nothing. I've checked the port 3000 in cmd with netstat -a -n -o and it says that the port is listening (so I guess it is working). So what is preventing me from accesing to that port.
Here it my JS files:
server.js:
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer();
server.listen(port);
app.js:
const { request } = require('express');
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.status(200).json({
message: 'It works'
});
})
module.exports = app;
Add the required app to the createServer call:
const server = http.createServer(app);
In this way the http server can route your http requests to it.
Could process.env.PORT be set somewhere, causing your app to be hosted on that port instead?
An easy way to check would be to console.log the PORT variable in your script, and see if it has any value.
If it does have a value, trying going to localhost:PORT
I have an https expressjs server with websockets (using the 'ws' package). As far as I understand sockets and ports, I should be able to add a route alongside the websocket connections. The main use-case is so that the server can be curled (none of the ws curl requests I've seen online worked.)
Unfortunately I only have 1 port to use for the server and websockets. How can I set this up so that app and server can both listen on the same port?
I've seen a few comments on SO that indicates that it can be done, but no code examples, or it's for very different packages.
I'm using the 'ws' package: https://www.npmjs.com/package/ws
const port = 8888;
const http = require('http');
const https = require('https');
const express = require('express');
const websocket = require('ws');
const app = express();
app.use( express.static('public') );
app.get('/curl', (req, res) => res.send('Hello World')).listen( port );
const httpsServer = https.createServer( credentials, app );
const wss = new websocket.Server({ server: httpsServer });
httpsServer.listen( port, function listening(){
console.log( 'listening on ' + port );
});
Currently I get the "EADDRINUSE" error since I'm using the same port for two 'servers'.
FOLLOW-UP
Express app doesn't need to also listen if another server is.
To curl https, you have to provide the cert details, or use the '-k' (insecure) method.
Your code shows you trying to start two servers on the same port.
This line creates a new http server and attempts to start it on port 8888:
app.get('/curl', (req, res) => res.send('Hello World')).listen( port );
These lines create a new https server and attempt to start it on port 8888 also.
const httpsServer = https.createServer( credentials, app );
httpsServer.listen( port, function listening(){
console.log( 'listening on ' + port );
});
You cannot do that. If you just want one https server that works for both your web requests and your webSocket (a common way to do things), then change your code to this:
const port = 8888;
const https = require('https');
const express = require('express');
const websocket = require('ws');
const app = express();
app.use( express.static('public') );
app.get('/curl', (req, res) => res.send('Hello World'));
const httpsServer = https.createServer( credentials, app );
const wss = new websocket.Server({ server: httpsServer });
httpsServer.listen( port, function listening(){
console.log( 'listening on ' + port );
});
which just removes the .listen(port) that operates on the app object because that will create an http server and start it on the 8888 port.
I am trying to use Express as my server in MEAN stack on AWS. However I've ran into a issue trying to setup subdomains. I have my main domain name domain.com and id like to have app.domain.com.. However I've tried everything I've found online to write the functionality into the server.js file and nothing works. How can I easily accomplish this to make the second function instead of loading on Port 8000 load up at my app.domain.com sub domain? Thanks in advance!
var express = require('express');
// Main Website
var web = express();
web.get('/', function (req, res){
res.sendFile('/web/index.html', { root: '.' })
});
var port = 9000;
web.listen(port);
console.log('Web Listening on port', port);
//Main Application
var app = express();
app.get('/', function (req, res){
res.sendFile('/app/index.html', { root: '.' })
});
var port = 8000;
app.listen(port);
console.log('Web Listening on port', port);
Update:
I tried using Vhost here but it loads the same thing for both the main domain and the sub domain and so it does not work. here is the code I used:
var express = require('express');
var connect = require('connect');
var http = require('http');
var vhost = require('vhost');
// Main Website
var web = express();
web.get('/', function (req, res){
res.sendFile('/web/index.html', { root: '.' })
});
var port = 9000;
web.listen(port);
console.log('Web Listening on port', port);
//Main Application
var app = connect()
app.use(vhost('app.domain.com', function (req, res) {
res.sendFile('/app/index.html', { root: '.' })
httpServer.emit('request', req, res)
}))
app.listen(8000)
I don't really need these to be on separate ports that was just something I was trying originally. But either way does not work still..
There's no need for any thing outside of node.js serving on one port. It's just a matter of routing based on the http header.
var express = require('express');
var http = require('http');
var vhost = require('vhost');
// Main Website
var webapp = express();
webapp.get('/', function (req, res){
res.sendFile('/web/index.html', { root: '.' });
});
//Main Application
var mainapp = express();
mainapp.use(function (req, res) {
res.sendFile('/app/index.html', { root: '.' });
}));
//Virtual Routing Application
var app = express();
app.use(vhost('app.domain.com', webapp));
app.use(vhost('domain.com', mainapp));
app.use(vhost('www.domain.com', mainapp));
app.listen(9000);
Since you're using AWS, you can use Application Load Balancer to achieve your goals.
Setup an ALB, and point both domains to the ALB CNAME.
Then you will need to create 2 target groups, one for app.domain.com and another one for domain.com.
Target Group: App
protocol: HTTP
port: 8000
Target Group: Web
protocol: HTTP
port: 9000
Attach your EC2 instance to both target groups
Target group > Targets > Edit > Add to registered
Finally you will have to add an HTTP listener to your ALB, and setup the rules to forward each domain to its target group.
After the rules are set, when you enter to app.domain.com the ALB will forward the request to your express app listening on port 8000, and when browsing domain.com the one listening on port 9000 will be used.
If you are using Route53 I recommend you to use Records Set to redirect both domain and subdomain to the same ec2 instance via the ip address then you can use ngix like the comments say in this post enter link description here
Using the load balancer (ALB) generates montly the minimum cost of 21.96USD but using Route53 it is minimum of 1USD or less.
If you dont want to use a proxy like nginx you can have s3 website hosting with a low cost, arround 6USD and the route 53 routing by 1USD minimum per month and if you have REST API services you can call from front end to your instance depending the site accessed with no problems.
Regards,
I have set up vmware workstation, Ubuntu 16.06 desktop as my guest machines, windows 10 as host.
nodejs 9.4.0
express 4.16.2
and simple server HTTP and express:
const http = require('http'),
PORT = 4000;
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('It works!');
res.end();
}).listen(PORT);
console.log("Listening on port " + PORT);
**/
/*** EXPRESS BASED TEST*/
const express = require('express');
const app = express();
PORT = 4000;
app.get('/', (req, res)=>{
res.send("it works!");
})
app.listen(PORT, 'localhost', ()=>{
console.log('Listening on port: ' + PORT)
});
/****/
What happens is, when I try to open test webpage from my host browser when guest runnin express - I get ERR_CONNECTION_REFUSED. BUT when i start simple http server - it connects! I tried to connect with telnet, ssh... turn of firewall... behavior is the same...
Is it something wrong with express? Is there a way to fix it?
The solutions is here:
Node.js connect only works on localhost
In my express app I make it listen on localhost, which is 127.0.0.1 and which is loopback address. After changing it to 0.0.0.0 the problem was solved.
I am pretty new to nodejs and very new to socket.io and express. I have some code that is working, but am having trouble understanding exactly why it's working.
My question for the below code is how does the express app know to listen on port 80? There's a server.listen. But there is no app.listen in the code. Yet app.post() readily accepts posted data.
Please consider the following code
var https = require('https');
var url = require('url');
var fs = require('fs');
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
//var io = require('socket.io');
var zlib = require('zlib');
app.use(bodyParser.urlencoded({extended: true }));
var options = {
key: fs.readFileSync('my.key'),
cert: fs.readFileSync('my.crt')
};
var serverPort = 80;
var server = https.createServer(options, app);
var io = require('socket.io')(server);
// log when the server is ready
server.listen(serverPort, function() {
console.log('Web socket server up and running at port %s', serverPort);
// this prints 80, as expected
});
app.post('/api', function (req, res) {
// working code is in here that receives the post variables and responds
}
With Express, the app object is just a request handler for some http server. If you call app.listen(), then the app object will create an http server for you. But, if you have created your own http server (which your code example does), then the app object just becomes a request listener on that server with this line of your code:
var server = https.createServer(options, app);
That creates the http server and registers app as a request listener (so it sees all incoming requests). This allows the Express app object to then process the routes that are registered with it to server routes like app.get(...) or app.post(...).
And, the port for Express is the port for the http server so it's the port that was used when the http server was created. What's important to understand here is that Express is not its own server. It's just a request listener for some http server.
In your code example, your http server is set up for port 80 so that's the port being used and Express gets registered as a request handler on all those incoming http requests on that port.
If you look at the source code for app.listen(), you see this:
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
All, it does is create an http server with the app object as a listener and then call .listen() on that new server.
the app does not have to know on which port to listen. Basically, server is your HTTP server binding which listens on port 80 in your example. var server = https.createServer(options, app); then tells the server to listen on port 80 for HTTP requests and forward them to your app. The app then does the routing stuff that links the function you sepcified with app.post(...) to a specific request URL (/api in this case).
TL;DR: The app does not need to listen, because the server is the only communication interface to the outside.