Cannot set an IP address on Express JS app - javascript

Trying to test an endpoint in express But keep getting 404 error.
var express = require("express")
var app = express()
//var http = require('http').Server(app)
app.get('/', function(req,res){
res.send('ok from end point')
})
var port = process.env.PORT|| 8080
var localhost = 'someLocalHost.med.gov'
console.log({'localhost':localhost,
'post':port})
//
app.listen(port,localhost,function(err){
if (err){
console.log('err')
}
else {
console.log('Listening')
}
})
When I go to
http://someLocalHost.med.gov:8080/
I get a 404 error

Localhost refers to 127.0.0.1. You can't just launch a server on any address that you want. If you're wanting to override localhost you can look into modifying your HOSTS file locally to setup an alias for localhost.

So I ended up http:// IP_ADDRESS:8080 and that took care of it.

Related

How can I make my localhost server available from external requests?

I'm running a simple nodejs server on my localhost on port :3434
const cors = require('cors');
const app = require('express')();
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.get('/ping/:anystring', (req, res) => {
console.log(req.params['anystring']);
res.send({
anystring: req.params['anystring']
})
});
app.listen(3434);
and I'd like to perform some ajax call from a website of mine.
I tried to configure the router port forwarding like so:
- name service: mylocalserver
- porta ragnge: 3434
- local ip: 192.168.1.19
- local port: 3434
- protocol: BOTH
but when I do
fetch(publicIP:3434/ping/hello).then(res => {
console.log(res);
})
I get error 404
Might anyone help me telling what I'm doing wrong?
You can't access your localhost server outside of your LAN unless you create a tunnel. I use ngrok.
There is an npm package for ngrok, but I couldn't get that one working, so I just manually start the server from terminal whenever I need to test an API.
Also you'll need http.
add this to your app.js:
const http = require('http');
const newPort = //your port here (needs to be a different port than the port your app is currently using)
const server = http.createServer(function(req, res) {
console.log(req); //code to handle requests to newPort
res.end('Hello World);
});
app.listen(newPort, function() {
console.log(`ngrok listening on ${newPort}`);
});
Now in terminal, after installing ngrok, use this ngrok http newPort where newPort = your port
You can view requests sent to your server by going to localhost:4040 (this might change depending on your system)
To send a request to your localhost, do this:
- name service: mylocalserver //not sure
- porta ragnge: ???
- local ip: //ngrok gives you a url in terminal when you start the server (I'm not sure if you can reference an IP)
- local port: newPort
- protocol: http //(ngrok gives you a different url for http and https)
You can use local tunnel
It maps your port on the localhost to a web url whithout the need to change your code

NodeJS disconnecting when attempt MongoDB connection

In my app.js file, I have the following code
var express = require('express');
var app = express();
var port = 8080;
var util = require('util');
var router = require('./base/js/routes.js');
//==================================================================
app.use('/', router);
// start the server
app.listen(port, function(request, response) {
console.log('Port 8080: Server Begins');
});
//==================================================================
var ipaddress = '123.456.789';
//==================================================================
var mongoose = require('mongoose');
var mongoURI = "mongodb://"+ ipaddress +":27017/test";
var MongoDB = mongoose.connect(mongoURI);
MongoDB.on('error', function(err) {
console.log(err.message);
});
MongoDB.once('open', function() {
console.log("mongodb connection open");
});
//==================================================================
The line var MongoDB = mongoose.connect(mongoURI);
is causing nodeJS not to work. I do not know why. NodeJS is on port 8080 and MongoDB is on port 27017.
I am fairly certain I installed mongodb package (and opened the port correctly). I just do not understand why nodeJS doesnt work when i include that connection line.
Side Note: Also I have the package forever installed: forever start -c nodemon app.js for nodeJS. If that is any relevance.
You are using wrong IP address format.
First try to connect with your local mongoDB instance if it work then you to check the IP address your trying to connect is correct or not.
Add the correct error message if problem still remain same.
change your mongod.conf file from /etc folder
In mongod.conf you need to change bindIp
If connection is local then set bindIp as
bindIp = 127.0.0.1
and if you want to use remote database then change bindIp as
bindIp = 0.0.0.0
then restart mongo service
hope this helps...

WebSocket on Heroku ERR_CONNECTION_REFUSED

I am trying to run a node js app on Heroku using WebSockets. However, I am not able to resolve this error (As seen in conosle of Chrome browser)
WebSocket connection to 'wss://myappname.herokuapp.com:27225/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I am using 'wss' since Heroku runs on HTTPS.
My client side code is :
$.get("https://myappname.herokuapp.com/port",function(data){
port = data;
console.log(data);
host = 'wss://myappname.herokuapp.com:' + port + '/';
ws = new WebSocket(host);
});
My server side code is :
var WebSocketServer = require("ws").Server
var fs = require('fs');
var express = require('express');
var app = express();
var http = require('http');
var port = process.env.PORT || 5000;
var request = require('request');
var server = http.createServer(app);
var serverOnPort = server.listen(port);
console.log("Server listening on port ",port);
var wss = new WebSocketServer({server: serverOnPort});
console.log("websocket server created");
Any help would be appreciated.
Thank You.
So it seems like I was trying to over-do it with the port number. Just using the host as wss://myappname.herokuapp.com/ works well.
I also found this problem. It seems Heroku will automatically route port number. It does's allow to specify port number in url. In my chrome, it show ERR_CONNECTION_RESET. This also happen with XMLHttpRequest. Port number still need when you test with localhost or another server which is not Heroku.

Express Server returns Cannot Get when trying to access index.html

I referred to the previously asked question on this but couldnt resolve it. I have Express server installed and trying to run Index.html file through it.
But I am getting 'Cannot GET /' as the response.
Here is the server.js through which I calling the index.html
var express = require('express');
var app = express();
app.get('index.html', function (req, res) {
app.use("/", express.static(__dirname));
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
Thanks in advance!!
When you access a directory on your hosted site, say the root directory of localhost on port 8080, using http://localhost:8080/ for URL, the browser does not send a request for 'index.html` to the server and just uses whatever the server sends back.
It's the express static middleware which in response to a browser request with no filename will check if the folder exists and (by default) return any index.html contained in the folder. So your line of code for routing, app.get('index.html') never executes, and the browser gives you the error message.
Here's a mini static express server if you want to try it.
var express = require('express');
var app = express();
app.use(express.static('../public')); // path to your public directory
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
If you want a simple static, folder-as-server kind of thing, you can do it without express way like "/public":
var fs = require("fs");
var host = "localhost";
var port = 8000;
var express = require("express");
var app = express();
app.use('/', express.static(__dirname));
app.listen(port, host);
I put this in the file express.js, so that is in the same folder than index.html (even associated .js with node.exe). This way the folder is the root of the server.

How to write a node express app that serves most local files, but reroutes some to another domain?

I'm working on a small webapp that normally is built with a relatively complex process and then deployed to WebLogic.
However, the portion I'm working on is using AngularJS, and is all HTML and Javascript. It normally makes ajax calls into another webapp on the same domain. To shorten my development cycle, I'd like to avoid a build process and just reload the browser page.
I think I can do this with "node express", but the details escape me. I've managed to define a very simple app that just serves local files, but now I have to figure out how to detect some of those paths as matching an expression, and reroute those requests to a request to an external domain.
So, if it gets a request for "/diag/stuff.html", "/foo/thing.html", or just "/index.html", it will send back the file matching the same path. However, if the path matches "/fooService/.*", then I have to send back the response from a GET to the same path, but on a different host and port.
This is my trivial app so far:
var express = require('express');
var app = express();
app.use("/", express.static(__dirname));
app.listen(8000);
Update:
I like the proxy idea, so I did a local install of "http-proxy" (I forgot and first did a global install) then changed the script to this:
var express = require('express');
var app = express();
var httpProxy = require('http-proxy');
var proxy = new httpProxy.RoutingProxy();
app.use("/", express.static(__dirname));
app.get('/FooService/*', function(req, res) {
"use strict";
return proxy.proxyRequest(req, res, {
host: "foohost.net",
port: 80
});
});
app.listen(8000);
This fails with:
<path>\server.js:4
var proxy = new httpProxy.RoutingProxy();
^
TypeError: undefined is not a function
at Object.<anonymous> (<path>\server.js:4:13)
What might be wrong here?
Update:
Would it be useful to see the contents of "console.log(httpProxy)" after that "require"?:
function ProxyServer(options) {
EE3.call(this);
this.web = this.proxyRequest = createRightProxy('web')(options);
this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options);
this.options = options;
this.webPasses = Object.keys(web).map(function(pass) {
return web[pass];
});
this.wsPasses = Object.keys(ws).map(function(pass) {
return ws[pass];
});
this.on('error', this.onError.bind(this));
}
Does that provide a clue for why "new httpProxy.RoutingProxy()" says it's undefined?
You can use http-proxy and forward requests to different host. To install http-proxy you need to run sudo npm install http-proxy. Code that will handle proxy will look like that:
httpProxy = require('http-proxy');
proxy = new httpProxy.RoutingProxy();
(...)
app.get('/fooService/*', function (request, response) {
"use strict";
return proxy.proxyRequest(request, response, {
host : externalHost,
port : 80
});
});
UPDATE
Above code is working for http-proxy ~0.10.x. Since then lot of things had changed in library. Below you can find example for new version (at time of writing ~1.0.2):
var httpProxy = require('http-proxy'),
proxy = httpProxy.createProxyServer({});
(...)
app.get('/fooService/*', function (request, response) {
"use strict";
return proxy.web(request, response, {
target: 'http://fooservice.com'
});
});
If redirects meet your need, then that's the easiest solution:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.use(app.router);
app.get('/fooService/*', function(req, res){
res.redirect(302, 'http://otherdomain.com:2222' + req.path);
});
app.listen(8000);
Note that it's generally considered good practice to use a subdirectory for your static files (like public above). Otherwise you could view your app file itself and anything else you keep in your application root!

Categories