Nodejs Server Hostname - http

Ok, so it seems pretty easy in Node.js to get the hostname of the request being made to my server:
app.get('/', function(req,res){
console.log(req.headers.host);
});
Is there an easy way to determine the hostname of my actual http server? For example, my server is running at the address http://localhost:3000 - can I programatically determine this address? I am using expressjs.

Yes you can using the;
var express = require('express'),
app = express(),
server = require('http').createServer(app);
server.listen(3000, function(err) {
console.log(err, server.address());
});
should print
{ address: '0.0.0.0', family: 'IPv4', port: 3000 }
you can also retreive the hostname for the os by the following;
require('os').hostname();

Related

Vite self signed certificate error when calling local API

I created a simple Vue3 app, and I'm trying to call another local API (on a different port) on my machine. To better replicate the production server environment, I'm making a call to a relative API path. That means I need to use a proxy on the vite server to forward the API request to the correct localhost port for my local development. I defined my vite proxy like this in my vite.config.ts file:
import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
import basicSsl from '#vitejs/plugin-basic-ssl'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
basicSsl(),
vue()
],
resolve: {
alias: {
"#": fileURLToPath(new URL("./src", import.meta.url)),
},
},
server: {
https: true,
proxy: {
'/api': {
target: 'https://localhost:44326', // The API is running locally via IIS on this port
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '') // The local API has a slightly different path
}
}
}
});
I'm successfully calling my API from the Vue app, but I get this error in the command line where I'm running the vite server:
5:15:14 PM [vite] http proxy error:
Error: self signed certificate
at TLSSocket.onConnectSecure (node:_tls_wrap:1530:34)
at TLSSocket.emit (node:events:526:28)
at TLSSocket._finishInit (node:_tls_wrap:944:8)
at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:725:12)
I already tried to add the basic ssl package, and I don't particularly want to install the other NPM package that is in the top voted answer. Why does the vite server complain about a self signed certificate when I'm trying to call another API on my local machine? What can I do to fix this?
you could try secure: false
server: {
https: true,
proxy: {
'/api': {
target: 'https://localhost:44326', // The API is running locally via IIS on this port
changeOrigin: true,
secure: false,
rewrite: (path) => path.replace(/^\/api/, '') // The local API has a slightly different path
}
}
}
the set of full options is available at https://github.com/http-party/node-http-proxy#options
Options
httpProxy.createProxyServer supports the following options:
target: url string to be parsed with the url module
forward: url string to be parsed with the url module
agent: object to be passed to http(s).request (see Node's https agent and http agent objects)
ssl: object to be passed to https.createServer()
ws: true/false, if you want to proxy websockets
xfwd: true/false, adds x-forward headers
secure: true/false, if you want to verify the SSL Certs
toProxy: true/false, passes the absolute URL as the path (useful for proxying to proxies)
prependPath: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path
ignorePath: true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request (note: you will have to append / manually if required).
localAddress: Local interface string to bind for outgoing connections
changeOrigin: true/false, Default: false - changes the origin of the host header to the target URL
preserveHeaderKeyCase: true/false, Default: false - specify whether you want to keep letter case of response header key
auth: Basic authentication i.e. 'user:password' to compute an Authorization header.
hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects.
autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.
cookieDomainRewrite: rewrites domain of set-cookie headers. Possible values:
false (default): disable cookie rewriting
String: new domain, for example cookieDomainRewrite: "new.domain". To remove the domain, use cookieDomainRewrite: "".
Object: mapping of domains to new domains, use "*" to match all domains.
For example keep one domain unchanged, rewrite one domain and remove other domains:
cookieDomainRewrite: {
"unchanged.domain": "unchanged.domain",
"old.domain": "new.domain",
"*": ""
}
cookiePathRewrite: rewrites path of set-cookie headers. Possible values:
false (default): disable cookie rewriting
String: new path, for example cookiePathRewrite: "/newPath/". To remove the path, use cookiePathRewrite: "". To set path to root use cookiePathRewrite: "/".
Object: mapping of paths to new paths, use "*" to match all paths.
For example, to keep one path unchanged, rewrite one path and remove other paths:
cookiePathRewrite: {
"/unchanged.path/": "/unchanged.path/",
"/old.path/": "/new.path/",
"*": ""
}
headers: object with extra headers to be added to target requests.
proxyTimeout: timeout (in millis) for outgoing proxy requests
timeout: timeout (in millis) for incoming requests
followRedirects: true/false, Default: false - specify whether you want to follow redirects
selfHandleResponse true/false, if set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event
buffer: stream of data to send as the request body. Maybe you have some middleware that consumes the request stream before proxying it on e.g. If you read the body of a request into a field called 'req.rawbody' you could restream this field in the buffer option:
'use strict';
const streamify = require('stream-array');
const HttpProxy = require('http-proxy');
const proxy = new HttpProxy();
module.exports = (req, res, next) => {
proxy.web(req, res, {
target: 'http://localhost:4003/',
buffer: streamify(req.rawBody)
}, next);
};

NGINX invalid port in upstream

I am using nginx as a proxy to a nodejs application. I have the same application running multiple times each on a different port. The request is directed to the correct application/port based on host name.
So
test1.domain.com would be proxied to 127.0.0.1:8000
test2.domain.com would be proxied to 127.0.0.1:8001
test3.domain.com would be proxied to 127.0.0.1:8002
When I hard code " proxy_pass http://127.0.0.1:8000;" Everything works fine.
Now I wrote a njs script to read a file in a users directory to get the port number based on the subdommain. Here is the script.
#inclusion of js file
js_include sites-available/port_assign.js;
js_set $myPort port;
function port(r) {
var host = r.headersIn.host;
var subdomain = host.split('.');
var fs = require('fs');
var filename = '/home/' + subdomain[0] + '/port';
var port = fs.readFileSync(filename);
port.trim();
return(port);
}
this does read the file and returns the port number correctly. I have verified this in the error logs, Because I get:
2020/01/21 04:26:46 [error] 2729#2729: *6 invalid port in upstream "127.0.0.1:8001
", client: 96.54.17.234, server: *.foundryserver.com, request: "GET / HTTP/1.1", host: "test1.foundryserver.com"
now when I tried to issue the directive: proxy_pass http://127.0.0.1:$myPort I get an internal server error and the error stated above.
Not sure what is the difference it the two. I can only think somehow using a variable $myPort is got weird characters or something.
There was some extra information in the port variable. I was able to store the port number in a json format and parse it in the js. {"port":"8000"} is stored in the file.
function port(r) {
var host = r.headersIn.host;
var subdomain = host.split('.');
var fs = require('fs');
var filename = '/home/' + subdomain[0] + '/myport';
var jport = fs.readFileSync(filename);
var port = JSON.parse(jport);
return(port.port);
}
by doing the json parsing it removed any unseen characters in the variable.

mup setup : Error: Timed out while waiting for handshake

Problem here is when I am trying to run command mup setup
there is error,where I am going wrong
Started TaskList: Setup Docker
[54.186.xx.xxx] - Setup Docker
events.js:183
throw er; // Unhandled 'error' event
My mup.js file looks like below
module.exports = {
servers: {
one: {
host: '54.186.xx.xxx',
username: 'ubuntu',
pem: '~/.ssh/mypem.pem'
}
},
app: {
name: 'myapp',
path: '/var/www/meteor/myapp',
servers: {
one: {},
},
buildOptions: {
serverOnly: true,
},
env: {
ROOT_URL: 'http://ec2-54-186-xx-xxx.us-west-2.compute.amazonaws.com',
MONGO_URL: 'mongodb://127.0.0.1:27017/myapp',
PORT: 3027,
},
docker: {
image: 'abernix/meteord:node-8.4.0-base',
},
deployCheckWaitTime: 60,
enableUploadProgressBar: true
},
mongo: {
oplog: true,
port: 27017,
version: '3.4.1',
servers: {
one: {}
}
}
};
Meteor version is 1.6.
Thanks in advance!
Nothing looks wrong with your mup.js file.
The problem may be that you cannot SSH with your current IP address. For instance, if you are using AWS, make sure that in the security groups your current IP address have access to it.
Not sure what is happening exactly, but there are a few potential issues:
deployCheckWaitTime: 60,
You could make this longer, eg 90 or 120 to give it more time to deploy (in case that is a problem)
path: '/var/www/meteor/myapp',
This might be the cause of the problem. Usually it is a relative path to the source code of the app, not where you deploy to, so typically it is something like ../app
ROOT_URL: 'http://ec2-54-186-xx-xxx.us-west-2.compute.amazonaws.com',
Presumably you are intending to use something like http://myapp.com/ for your app - that's what should go here.
In security groups, SSH source rule was MY IP, which I changed to anywhere then created elastic ip and bind it with instance. And now I can access login.
One can use this link to get help.
check your host ip.
I had same issue changing host ip fixed it for me.
Ip changes when you restart your VM es2 client.

meteor up listen tcp 0.0.0.0:80: bind: address already in use

I am using meteor up to deploy to a vps. I get the error in the title during the "Start Meteor" stage of mup deploy, along with a long list of
Error response from daemon: endpoint (appname) not found
Error response from daemon: No such container: (appname)-frontend
etc.
I have tried changing the imagePort value for docker in mup.js but I still get the same error, still for 0.0.0.0:80
In your case there is already an application that uses port 80. You can either remove that app and go ahead and redeploy, or you can change the port that your meteor application is going to be using, like so:
module.exports = {
servers: { ... },
meteor: {
name: ...,
path: ...
buildOptions: ...
env: {
PORT: 3000,
ROOT_URL: 'http://<your server ip>:3000',
MONGO_URL: ...
},
deployCheckWaitTime: 120,
enableUploadProgressBar: true,
}
};

How to get request’s HTTP headers with Socket.io?

I have an Express app running behind Nginx, so when I try to get the user’s IP, I always get 127.0.0.1 instead of the real one, which is set by Nginx in the X-Real-IP header. How do I get this header? Is there a way to have it via the socket object?
The code would be basically like that:
io.sockets.on( 'connection', function( socket ) {
var ip = /* ??? */;
/* do something with the IP…
… some stuff …
*/
});
To get the IP when you're running behind NGINX or another proxy:
var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
or for Socket.IO
client.handshake.headers['x-forwarded-for'] || client.handshake.address.address;
From: http://www.hacksparrow.com/node-js-get-ip-address.html

Resources