I am learning Node.js. While creating a web site, I will run the web site locally (on localhost). When it is deployed, it will run on other servers. My question is, how do I determine if a request is from localhost or not in Node? In ASP.NET, I could use Request.IsLocal. I'm trying to figure out how to do that in Node.
Thank you!
There's server.address() to get the server address.
And request has connection and socket objects, as both might hold remote address (in a remoteAddress property) depending on a type of current connection.
But if the server is behind a reverse proxy, you'll have to pull it from appropriate header, most likely x-forwarded-for. However I'm not sure if that holds if proxies are chained.
So, to conclude, you'd do something along the lines of:
function cliAddress(req) {
return req.connection.remoteAddress || req.socket.remoteAddress || req.headers['x-forwarded-for'];
}
server.isLocal = function(request) {
return server.address() === cliAddress(req);
}
And if you use express.js see Express.js Req.IP API.
Related
I'm trying to set up push notifications for a browser web app.
I found the following code can be used to subscribe to a push server. Running a simple push server locally seems to work fine, but
Q: I was wondering how I would specify the push server if it wasn't local?
I mean, how would the browser know where to subscribe to just by looking at the public key of the server?
function createNotificationSubscription(pushServerPublicKey) {
return navigator.serviceWorker.ready.then(
(serviceWorker) => {
return serviceWorker.pushManager
.subscribe({
userVisibleOnly: true,
applicationServerKey: pushServerPublicKey
})
.then((subscription) => {
console.log("✅ User is subscribed.", subscription);
return subscription;
});
}
);
}
References:
https://developer.mozilla.org/en-US/docs/Web/API/PushManager/subscribe
how do I specify the push server [...]?
You don't.
if it wasn't local?
There is a misunderstanding.
The push server will always be a fixed server given by the browser vendor.
It basically works like this:
You subscribe()
This request goes to the notification server of the browser vendor (mozilla, google, ...).
That server will create a so called push endpoint - just a fancy word for URL. This URL serves as a mailbox: If someone sends a message to it, the push server (still being the server of the browser vendor) will forward it to the browser (client).
The server will return the push endpoint and some other information as a result of your initial subscribe().
Currently only the push server and your web app know about the push endpoint....
So your web app needs to the whole result of subscribe to the application server (which is your server).
Now your server is able to use that information to send messages to the push server. The push server will then forward the message to the client.
Here's also a flow chart depicting the flow with a little more detail in regard of the different players:
Push service: Service running on the browser vendor's server
Subscription information: URL of the push endpoint along with some keys.
I'm trying to retrieve the IP address of a new socket on the client side.
like so
var socket = net.Socket()
console.log(socket.remoteAddress)
However, this prints undefined to the console
On the server side, socket.remoteAddress is exposed with no issues at all using this code.
net.createServer(function(socket){
console.log(socket.remoteAddress, socket.remotePort)
}).listen(4000)
So my question is, am I experiencing a bug, or am I misunderstanding how Socket/TCP connections are handled.
I understand that in TCP, typically the client port is chosen at random, but I don't imagine this should make it undefined as I'm experiencing- and at the very least, the public IP should be available to the API so long as I'm connected to a network. Admittedly, I am a bit of a novice with networking, but this seems a bit weird.
recently, external server(REST API) told me to use Keep-alive for my request. That's great, since I use request.js(node 8) I found "forever" option:
forever - set to true to use the forever-agent Note: Defaults to http(s).Agent({keepAlive:true}) in node 0.12+
To test if it's working I created my own server in Node8 using Koa.js and Node script where I create array of 100 GET request to my server and after that, I Promise.all them.
However, I don't how can I check if it's using the same agent, if it's working correctly.
Do you have any ideas, how from client(or server) point of view I can check that?
Is keep-alive enough proof that all request for certain domain are using the same agent in 1 Node.js process?
On the client, you can try to capture the socket which is used to send the request using the socket event. You can verify that they are using the same sockets on the client.
req.on("socket", function (socket) {
//if saved socket is empty save it
//else check if its using the saved socket
}
I'm trying to allow access to socket.io only if the website the connection is coming from is one of the whitelisted subdomains on my server. The best would be if I could check the origin subdomain everytime a client connects to my socket.io server. I tried finding out how to do it, but haven't found a good solution yet.
The only thing that comes close to a solution is this answer to a related question. However - I'm not sure if that's the best way to do it and if that even works in my case and can't be faked via javascript.
TLDR: How do I treat socket.io requests differently based on their origin? If that's not possible: How do I host two socket.io servers on two subdomains, but same port?
Regarding duplicate flag: My Question is entirely different. I cannot use namespaces as a solution since I can't trust the client side javascript running on some subdomains. Therefore these subdomains could just join a different namespace, which would make my efforts to separate them pointless.
I found this answer with the help of some guy on the socket.io slack server.
io.on('connection', function (socket) {
var subdomain = socket.handshake.headers.host.split('.')[0];
if (subdomain === 'allowed') {
socket.on('login', /* ... */);
} else {
socket.on('login', function () {
console.log('login disabled, wrong subdomain');
});
}
}
I don't know it it's reliable or can be modified by malicious client javascript, but it was looking quite good while I was testing it.
I added the this modifie code to the express/socket.io middleware function so it gets called on every request: connect, disconnect, and streaming.
I also use the express-subdomain npm
https://www.npmjs.com/package/express-subdomain
app.sio.use((socket, next) => {
var subdomain = socket.request.headers.host
sessionMiddleware(socket.request, {}, next)
})
In my application i have created many methods in node.js file.How can i call the particular method from client side javascript.
Below is my node.js file
exports.method1=function(){
}
exports.method2=function(){
}
exports.method3=function(){
}
Your client should send a message, for example:
socket.emit("callMethod", {"methodName":"method3"});
And in your server:
socket.on("callMethod", function(data) {
if(data["methodName"] == "method3") {
exports.method3();
}
});
You don't call methods directly, you send events/messages.
I would avoid using sockets unless you really need to, from my experience they can be expensive. Sockets are great for intensive applications where a user stays engaged for awhile, otherwise I would suggest using a RESTful setup with javascript and node.js, for example:
http://blog.modulus.io/nodejs-and-express-create-rest-api
this way the socket doesn't always have to be open which causes more overhead anyway. REST will use http requests whereas sockets you will have direct connection via TCP. REST is better if your app won't be constantly engaging a user, but rather have updates here and there.