express: getting the URL of the running instance globally - node.js

I am using express 4.x and I want to know if there is a way to get the URL (for instance localhost:7777 or mydomain.com) during the run-time?
I have several requests, where I need to return images saved on the same server with the full URL, but the IP address / port is changing, therefore I would like a solution, where I can save the URL globally. (not within a get/... request)

I believe you access the app instance:
var app = express();
....
app.address() //address
app.port() // port

Related

How to get IP address of Computer, in which the node js server runs, to use in react application?

I wanna get the IP address of the computer that the node js server runs in, in order to use the correct URLs of the server inside React application.
for example when I fetch a "http://localhost:<port>/api" from another device in the same network it doesn't work.
I tried to provide the computer IP address manually, but after sometime, a day or two, the IP changes and then I have to open provide the IP address again.
so, I'm asking if there's a way to provide the IP address dynamically to React application?
You can either use the Node networkInterfaces Out Of the Box feature, or use a package that handles parsing request and extracting data for you.
const os = require('os');
const networkInterfaces = os.networkInterfaces();
console.log(networkInterfaces);
If you do not want to parse the response yourself - have a look at highly popular package: request-ip.
https://www.npmjs.com/package/request-ip
const requestIp = require('request-ip');
// inside middleware handler
const ipMiddleware = function(req, res, next) {
const clientIp = requestIp.getClientIp(req);
next();
};
for anyone facing the same problem, I found a simple solution which is to specify a "proxy" in package.json file of the React application:
in package.json file
...
"proxy": "http://192.xxx.xx.xxx:<port>"
...
this way you're telling react to proxy the requests to the backend server when making a request for example to "/api/v1" instead of specifying the whole url like this "http://192.xxx.xx.xxx:<port>/api/v1"
and whenever the IP changes you just edit the "proxy" value and restart the dev server.

Https createServer, load cookie and load clients index.html

I am trying to setup a login system on a website.
In order to do that, I have to load http only cookies.
In order to load them, I have to send them back to the client via the response object in the createServer function when https starts up.
I have successfully done that via here:
setting up https cookie in nodejs
The problem is twofold.
The https server cookie only loads if I include the port number in the url.
How do I get it to load without including the port number?
When the server kicks in and loads the cookie, the static index.html that was always supposed to load on the client, doesn't load and instead all i get is what was written into the response object on the server. How do I get to load the cookie, and just load that static html file?
I have tried sending in the entire html file as a respnose from the server side. But I'm not sure about that, plus i get MIME type problems in the browser.
I am not sure for the first part but for 2nd one,
you have to properly mention about response data type in response header.
so your should be something like this one:
var app = express(); app.get('/test', function(req, res) { res.sendFile('views/test.html', {root:__dirname}) });
For your first part of the question "How do I get it to load without including the port number?" You can try creating virtual host e.g for localhost:3000 will be something.xyz.
And for your second part you need to serve index.html with render method as follow
server.get('/', function (req, res) {
res.render('index', { greeting: 'Welcome' });
});
Where index is you static file inside view directory.
I've created a small demo, that might get you on the right track:
https://github.com/bergur/simple-server-with-websocket
This example includes:
https web server
websocket server
logic to get the cookies
serving a temp.html file without express
example of javascript class
example of dependency injection in nodejs

How to get url and port from app.js using node/express

I want to get the value of the url from app.js so I can assign it to app.locals
an use it on the templates. How do I do it from app.js ? I am using express js
generator. so my main file is the app.js. I just want to get the current
url/domain and put it on app.locals, like a define variable.
app.locals = {
socket_io_host: 'http://localhost:3001',
socket_io_port: "3001",
};
If I am not wrong you want the IP address of the server on which you have hosted the application. If this is the case then please use the following module:
Node IP
Other case is if you want the IP address of the requesting client then you can use the following code:
req.headers['x-forwarded-for'] //IF APP IS BEHIND PROXY
req.connection.remoteAddress //IF APP IS NOT BEHIND PROXY

Express JS access remotely

I have an app set up using BackboneJS, NodeJS and ExpressJS. I have trouble accessing my routes from my application. But I can access my routes directly in my browser and see the output.
For example this works:
http://test.myserver.com:3000/employees/1
(where test.myserver.com is my server address accessible externally)
My express server declaration is as follows:
var express = require('express'),
employee = require('./routes/employees');
var app = express();
app.get('/employees/:id', employee.findById);
app.listen(3000);
My problem is that when I try to access the route through my application I get an access error.
http://test.myserver.com/pages/index.html#employees/1
GET http://localhost:3000/employees/1?callback=jQuery19107984810129273683_1457829695460&_=1457829695461 net::ERR_CONNECTION_REFUSED
How can I access my routes from within my application using Express?
I see an issue. You say you're loading a web page at:
http://test.myserver.com/pages/index.html#employees/1
But, the URL request is for:
http://localhost:3000/employees/1?callback=jQuery19107984810129273683_1457829695460&_=1457829695461
Those are different domains and different ports. It looks to me like jQuery sees that this is a cross origin request and is trying to turn it into a JSONP request, but your server is not support JSONP.
Likely what you need to do is to get the Javascript in your web page to be requesting the SAME origin (same domain, same port) that the web page is loaded from. Then, it will not be cross origin request and it should work (if nothing else is wrong).
Please show us the relevant Javascript in your web page that is making this request so we can advise more specifically on how to fix it.
Also, if you're expecting your node.js server to serve your web pages, you will need node.js code to do that (you don't show any of that code) since node.js does not serve any pages by default (unlike some other web servers).

how to develop a node.js app which supports multitenancies

I have a requirement that I want to serve multiple sites(host names) with the same port number.
These sites share the same code files, while only differ in that they have different site configurations and file upload folders.
basically it's just a cms which can host various domains, and usually each domain will have its own themes and configurations and of course db connections.
is there anybody who can give me some directions on this? Thanks very
much.
var subdomains = require('express-subdomains')
, express = require('express')
, app = Express.createServer()
// example: api.example.com/user -> '/api/user'
subdomains
.use('api')
.use('other.vanity.domain')
app.use(subdomains.middleware)
app.get('/api/user' function (req, res, next) {
// ..
})
app.listen()
https://github.com/tblobaum/express-subdomains
Each site should have it's own process and port, and you should proxy requests depending on the hostname.
You can use node-http-proxy or bouncy for proxy each site to its specific port. Another option is to use Express's vhost feature: https://github.com/visionmedia/express/blob/master/examples/vhost/app.js
You can easily support multiple domains from a single HTTP server codebase (see virtual hosting), you will just need to implement logic in your handlers to inspect the request host (e.g. in the Host HTTP header) and act conditionally based on its value. Then you can have any number of DNS names point to your server and act differently on them.
Here's an example:
http.createServer(function (request, response) {
var host = request.headers['Host'];
if (host == 'domain1.com') {
// Execute logic based on that host.
} else if (host == 'domain2.com') {
// Execute other logic...
}
}).listen(8080);

Resources