I have two ports running on my local network for a server: 27017 which is the port for the MongoDB, and 3000 which is the port for my nodejs app. I then connect the two using mongoose connect while listening on port 3000.
var db = mongoose.connect('mongodb://localhost/test')
app.listen(3000, () => {
console.log('listening on port 3000')
})
Previously I was trying to connect to the server via a web browser using http://(server ip):27017 but my GET which was written in my NodeJS app would never get called.
app.get('/', (req, res) => {
res.send('hello world')
})
I switched the port to 3000, http://(server ip):3000 and finally I got a response from my GET.
So is this how clients should be connecting to their servers? Through their nodejs app and not to the database? Should clients also connect to the nodejs app when using TLS with HTTP?
CodePudding user response:
A browser client should connect to your web server, not to the database so in your example above, that would be on port 3000.
So is this how clients should be connecting to their servers? Through their nodejs app and not to the database?
Yes. The database is there for your server to use, not for the client to use directly. Any client interaction with the database happens indirectly through your server.
Should clients also connect to the nodejs app when using TLS with HTTP?
If the server is running locally only using localhost to access it, then there is likely no need for https.
It is generally recommended to run public servers on https these days. That would mean that you would get a certificate from a certificate authority like Let's Encrypt and use https.createServer()
with the https credentials option in a general scheme like this example from the Let's Encrypt website:
// Dependencies
const fs = require('fs');
const https = require('https');
const express = require('express');
const app = express();
// Certificate
const privateKey = fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem', 'utf8');
const certificate = fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/cert.pem', 'utf8');
const ca = fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/chain.pem', 'utf8');
const credentials = {
key: privateKey,
cert: certificate,
ca: ca
};
app.use((req, res) => {
res.send('Hello there !');
});
// Starting https server
const httpsServer = https.createServer(credentials, app);
httpsServer.listen(443, () => {
console.log('HTTPS Server running on port 443');
});
Note, you would usually run an https server on port 443. Then, you would connect to this server using the https
protocol, not http
. You would not need to specify the port in the browser URL if you were using 443 (the default port number for https), but would need to specify the port if not using port 443.