how can i host a website multiple times on nodejs? - node.js

const { response } = require('express');
const express = require('express');
const { request } = require('http');
const app = express();
app.listen(3000, () => console.log ('listening at 3000'));
app.use(express.static('public'));
app.use(express.json({limit: '1mb'}));
app.post('/api', (request, response) => {
console.log('Incoming data:');
console.log(request.body);
});
my code is here. my question in the title. how can i host public folder in the code more than one with different ports and ip's?

To my knowledge I do not believe it is possible to do this without creating lots of express servers which in my opinion is not best practice and may crash your server.
You may want to look at alternate solutions such as Nginx. You could setup Nginx virtual hosts to host multiple files.

Related

How to run different server on same port?

I have created 2 server with express and node.js and now I want to run both the server on the same port which is localhost:8000 with different end points.
How it can be done or what can be the approach for it?
Attaching the server code for reference:-
Server1:-
const express = require("express");
const cors = require("cors");
const app = express();
const axios = require('axios');
app.use(cors());
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
const PORT = 8000;
app.get("/WeatherForcast", function (req, res) {
axios.get('https://localhost:7173/WeatherForecast')
.then(response => {
res.status(200).json({ success: true, data: response.data});
})
.catch(error => {
console.log(error);
});
});
app.listen(PORT, function () {
console.log(`Server is running on ${PORT}`);
});
Server2:-
const express = require("express");
const cors = require("cors");
const app = express();
const axios = require('axios');
app.use(cors());
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
const PORT = 8000;
app.get("/UserData", function (req, res) {
axios.get('https://localhost:7173/UserData')
.then(response => {
res.status(200).json({ success: true, data: response.data});
})
.catch(error => {
console.log(error);
});
});
app.listen(PORT, function () {
console.log(`Server is running on ${PORT}`);
});
Currently when I run it, one server runs and for other server an error is displayed that port 8000 is already in use.
You can't run two servers on the same port. The OS and TCP stack won't allow it.
The easiest solution is to use two endpoints on one server.
If you have to have two separate servers, then you would run them both on separate ports (neither of which is the public port) and then use something like nginx to proxy each separate path to the appropriate server.
So, the user's request goes to the proxy and the proxy examines the path of the request and then forwards it to one of your two servers based on the path of the request (as setup in the proxy configuration).
Two different servers can not be hosted on same port as it will give the error i.e "this port is currently is use" something like this.
The thing that can be done is instead of creating multiple server you can create a single server and define different endpoints to manage the code flow.
it is not possible to run different servers on same port

Debian server, Node js Port 3000 listening But cant access via browser

On my debian server, I installed node and then started node server on port 3000. The server is running, but it isn't visible from the browser
Now when I try to get it running via my domain or via my ip(for example xx.xxx.xx.xx:3000) or my domain (my-domain.com:3000) in both cases it doesn't work. I think I don't quite get the concept and I tried to search for a billion different things, but I can't find the solution to my problem. Could someone tell me, if I need to setup something else, too?
My server js code is
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
server.listen(3000, () => {
console.log('listening on *:3000');
});
io.on('connection', function (socket) {
socket.on( 'new_message', function( data ) {
io.sockets.emit( 'new_message', {
message: data.message,
date: data.date,
msgcount: data.msgcount
});
});
});
Error i got
You need to listen for GET requests in order to respond to them.
Try adding something like:
app.get('/', function (req, res) {
res.send('GET request test.')
})
In your case make sure you add the route before passing the app to the http.createServer() method, or otherwise just use something like app.listen(3000).
More info in the docs: https://expressjs.com/en/guide/routing.html
why are you using express and http both packages.
you can run server by either of them.
and then add a get route for it.
import { createServer } from "http";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer, {
// ...
});
io.on("connection", (socket) => {
// ...
});
httpServer.listen(3000);
I hope this will work!

Device login detection with node.js and react.js

I need to restrict users to login from multiple devices. I'm using react.js at the frontend and node.js as the backend. Which is the most reasonable way to handle this task?
I can not imagine how you can identify user browser 100 %. Cookies are browser based,so that could not solve the problem. Try Matteo Collina's pino logger, I think that it has many options.so you can choose most suitable for your task.
For example,this simple code
const express = require('express');
const pino = require('pino');
const expressPino = require('express-pino-logger');
const logger = pino({ level: process.env.LOG_LEVEL || 'info' });
const expressLogger = expressPino({ logger });
const PORT = process.env.PORT || 3000;
const app = express();
app.use(expressLogger);
app.get('/', (req, res) => {
logger.debug('Calling res.send');
res.send('Hello World');
});
app.listen(PORT, () => {
logger.info('Server running on port %d', PORT);
});
would show
"level":30,"time":1613817528986,"pid":17345,"hostname":"jholmes","msg":"Server running on port 3000"
You can pick IP,but would dynamic Id's you can not point pot to single user.
React also has plenty libraries for auth(ajv).

Using .createServer to make a public website

So I have a file I want to host from my computer, and I want to be able to listen at the port for various reasons. I'm using
const port = [number]
http.createServer((req, res) => {
let responseCode = 404;
let content = '404 Error';
const urlObj = url.parse(req.url, true);
if (urlObj.query.code) {
const accessCode = urlObj.query.code;
}
if (urlObj.pathname === '/') {
responseCode = 200;
content = fs.readFileSync('./index.html');
}
res.writeHead(responseCode, {
'content-type': 'text/html;charset=utf-8',
});
res.write(content);
res.end();
})
.listen(port);
and all that good stuff makes it where I can have a local file, http://localhost:[number]. However, I'm not exactly sure how I can use this same method for hosting on an online website, one in which I upload my code to the website then have the website started from my computer (using the create server). Does anyone know how to basically create a server that's not private/local, but instead is public (and yes I can use a web host).
I recommend using the express framework as it greatly simplifies serving static files. It would be as simple as the following:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.static(__dirname + '/public'));
app.listen(port , () => {
console.log(`Server is running at port ${port}`);
});
With above code all that's left to do is to create folder called public in your app directory where you place your html/css/js files.

How to use Gun as an express route?

I'm trying to use gun in an express/node project, however I want to mount the endpoint as /db. I had hoped the following code would work but keep getting a Route.get() requires callback functions error:
var express = require('express');
var Gun = require('gun');
var app = express();
var port = 8080;
var gun = new Gun({
file: './data.json'
});
// mount the gun db server
app.get('/db', gun.router);
// regular express route
app.get('/', function(req, res) {
res.send('other stuff...');
});
// start the server
app.listen(port, function () {
console.log('Web server listening on port ' + port);
});
Any suggestions?
Doherty!
GUN can be used with express, but it is not an express route. For example, lets first go over a simple gun server mounted with express:
var express = require('express');
var Gun = require('gun');
var app = express();
app.use(Gun.serve).use(express.static(__dirname));
var server = app.listen(80);
Gun({file: 'data.json', web: server});
( https://github.com/amark/gun/blob/master/examples/express.js )
GUN's API is now available in the browser at:
<script src="http://YOURSERVER.com/gun.js"></script>
<script>
var gun = Gun('http://YOURSERVER.com/gun');
gun.get('key').get('hello').put('world!');
gun.get('key').get('hello').on(function(data){ console.log(data) });
</script>
GUN is not available as an express route. For example, this does not work:
http://YOURSERVER.com/data/key/hello?put=world!
Why?
GUN is a realtime database, if you use a REST or CRUD routes with express as its API, then you lose the realtime capabilities. Meaning you would have to write your own custom long-polling implementation, which defeats the point of having an express route.
I understand, but I still want a REST or CRUD API for GUN?
It should not be hard to create an HTTP route that proxies gun. Here is some pseudocode that should help get you started. If you build it, please make it an Open Source module on NPM so others can enjoy it!!!
// this is pseudocode!!!
app.get('/data', (req, res) => {
path(req).val(data => res.send(data))
});
app.put('/data', (req, res) => {
path(req).put(req.param.put, ack => {
res.ack? 0 : res.ack = res.send(ack)
})
});
var path = (req) => {
var ref = gun;
req.path.split('/').forEach(key => ref = ref.get(key));
return ref;
}
Let us know if you build it! As always, the community chatroom is friendly and active. Ask for help there, and ask questions here. Thanks for making this a SO question!

Resources