Start a nodejs tcp server within nodejs app - node.js

My use case to start and stop a tcp server within the nodejs app that i am writing.
So I have an index.js which starts up a web server on port 3000. Using endpoints '/' and '/start', i would like to get the status of the server and start the server respectively. I would also like to display the status of the server via socket.io but that's for later.
Right now, I am getting a
TypeError: Converting circular structure to JSON
error which I think it is probably attributable to returning the server object below.
How can I start and stop the tcp server via REST endpoints?
// server.js
'use strict'
var net = require('net')
var server = false
exports.get = function() {
return server
}
exports.start = function(port, host) {
if (!server) {
server = net.createServer(handleConnection).listen(port, host)
return server
}
}
exports.stop = function() {
if (server) {
server.close(() => {
console.log(`server.close called`)
})
server = null
return server
}
}
function handleConnection(socket) {
...
}
Here is the index.js
// index.js
'use strict'
var net = require('net')
var http = require('http')
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var addServer = require('./server')
var PORT = 3000
var HOSTNAME = '127.0.0.1'
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
var server = http.createServer(app).listen(PORT, HOSTNAME, () => {
console.log('http.createServer started')
})
app.get('/', (req, res) => {
// get addServer status
addServer.get()
res.status(200).json({ status: 'success', command: addServer.get() })
})
app.get('/start', (req, res) => {
// start addServer
addServer.start(9000, '127.0.0.1')
res.status(200).json({ status: 'success', response: '' })
})

You're trying to return server object via json.
res.status(200).json({ status: 'success', command: addServer.get() })
Try without it.
res.status(200).json({ status: 'success' })

Related

request body is not working - MYSQL and Node JS

I'm trying to create this API with NodeJS, Express and Mysql but when testing on Postman, while the code is working to update the values on the database, it doesn't read the info I insert in the body of the request. For example, I can access the params info (codAluno), but not the request body (Empresa_Atual).
I have two files for the API: routes.js and index.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./routes')
const port = 3000
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.use(bodyParser.json())
app.get('/', (request, response) => {
response.json({ info: 'API' })
})
app.get('/alunos', db.getAlunos)
app.get('/alunos/:id', db.getAlunoByCod)
app.post('/alunos/:id',db.updateAluno)
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
and routes.js
const mysql = require('mysql');
// Set database connection credentials
const config = {
host: 'localhost',
user: 'user',
password: '',
database: 'student',
};
// Create a MySQL pool
const pool = mysql.createPool(config);
const updateAluno = (request, response) => {
const codAluno = parseInt(request.params.id)
var Empresa_Atual = request.body.Empresa_Atual
pool.query('UPDATE aluno SET `Empresa_Atual`= ? WHERE `codAluno` = ?', [Empresa_Atual, codAluno], (error, result) => {
if (error) throw error;
response.send('User updated successfully.');
});
}
This is the request I'm sending via postman
For example, the variable Empresa_Atual is always null even though I assigned it to the request body.
Can anyone help?
Thanks!
I had the same problem. I had the following: req.params.id. I then changed it to req.params['id'] and it started working. Apparently, the req.params was an object instead of a single value.

Nodejs api not accepting the POST method, error 405

I already search for existing question, but none of them worked for me.
I've simple nodejs methods, on my localhosts they work fine, but when I hosted them on a server (nginx), my post method gives error of 405 (not allowed), even though I've allowed CORS
Here is my server file
var http = require('http');
var mongo = require('mongodb');
var cors = require('cors')
var express = require('express');
var app = express();
app.use(cors());
var DB = 'mongodb://localhost:27017/ClientApp';
app.use(express.json());
const clientRoutes = require('./client');
const authRoutes = require('./auth');
app.get('/api/status', (request, response) => {
// console.log(request.body);
response.json({ status: ' Server Running' });
});
app.use('/', clientRoutes);
app.use('/', authRoutes);
app.listen(3000, (resp) => {
console.log('server listening at port number: ', 3000);
});
and here is the route that is not working
app.post('/api/register', (request, response) => {
console.log('Request body: ', request.body);
mongo.connect(DB, (error, client) => {
console.log('Connect to Database successfully');
const connectedDb = client.db('ClientApp');
data = request.body;
if (data.username) {
connectedDb.collection('Users').insertOne(data, (error) => {
if (error)
console.log('Error occured while registration')
else {
response.status(200).send({ status: 'Response Received Successfully', code: 200 })
console.log('User registered successfully!');
}
})
} else {
response.status(204).send({ status: 'Please include the user details', code: 204 })
}
})
});
I see you have your app's listening port set to 3000. You will need to verify in the nginx.conf file that is the port the traffic is being set to from the reverse proxy. Depending on how things are setup, there may be an environment variable set indicating which port the app should listen to. This variable is commonly called PORT.
If the PORT environment variable is being set you can change your code like so:
app.listen(process.env.PORT || 3000, (resp) => {
console.log('server listening at port number: ', 3000);
});
In case you're not aware, using process.env.PORT || 3000 will use the value process.env.PORT if it is set. If it is falsy then 3000 will be used.
For NGINX have a look at the nginx.conf at the server entries to determine how the reverse proxy is sending traffic to backend apps.

Socket.io my middleware for custom Id does not works

i followed instructions in this link Rohit Nishad and my data is well passed from client to server.
But the ID is not passed from my middleware with the overwritten function. A new Generated ID is shown on socket.io connection.
Any idea what's going wrong please ?
I'm using socket.io v3.1.0
server.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const socketIO = require('socket.io');
const io = socketIO(server, {
cors: {
origin: "http://localhost:4200",
methods: ["GET", "POST"]
},
});
// Socket.io configuration
io.of('/notification').use((socket, next) => {
console.log('(socket.handshake.query.userId) :', socket.handshake.query.userId);
io.engine.generateId = (req) => {
socket.handshake.query.userId;
};
next(null, true);
});
io.of('/user').use((socket, next) => {
io.engine.generateId = () => socket.handshake.query.userId;
next(null, true);
});
io.of('/notification').on('connection', socket => {
console.log('[Notification] - New client connected : ID ', socket.id);
});
io.of('/user').on('connection', socket => {
console.log('[User] - New client connected : ID ', socket.id);
});
const serverPort = process.env.PORT || port;
// Launch server
server.listen(serverPort, () => {
console.log(`App is running ! Go to http://${host}:${port}`);
});
and console output:
App is running ! Go to http://localhost:3000
(socket.handshake.query.userId) : 5ffdb966c204c85d4061bf9f
[Notification] - New client connected : ID EjdB0uz8K7NSGWYyAAAB
[User] - New client connected : ID E4tu9sKXliWTFEcsAAAC

Why my POST request work only with debugger?

I try to write CRUD and checking it up with Postman.
When I use a debugger at the end of the post request it's working.
Problem: When I remove the debugger and try to run the code nothing happens - only error: "Could not get any response". How can I make my post to work well without debugger?
***For example, I send this as JSON through postman like this:
{
"id":3,
"name": "Ron",
"phone": "01323133333"
}
this is the relevant code:
index.js:
const express = require('express');
const app = express();
db = require('./db');
app.use(express.static('public'));
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const port = 1400;
app.listen(port,()=>{
console.log(`Server is running on port ${port}`);
})
//post request:
app.post('/user' , (req,res)=> {
const {body} = req,
{id,name,phone} = body
db.query(`INSERT INTO public.users(
id, name, phone)
VALUES (${id}, '${name}', '${phone}');`,(err,dbRes)=>{
if(err)
res.status(400).send(err);
else
{
res.send(dbRes.rows);
}
})
})
db.js:
const {Client} = require ('pg');
const client = new Client ({
user:'postgres',
host:'localhost',
database:'nodeapp',
password:'123456',
port:5432
})
client.connect();
module.exports = client;
Thank you !

How to send message to frontend in case of MongoDb connection Failed

Is there any way to send error to frontend on mongoDb connection error.I had tried in a different different way but I didnt get a solution.
var express = require('express');
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
var store = new MongoDBStore(
{
uri: config.connectionString,
collection: 'tbl_session'
});
// Catch errors
store.on('error', function(error) {
app.get('/',function(req,res){
res.send('NOT Connected....')
});
});
You can use web sockets to push this information to the UI.
const express = require('express');
const app = express();
const path = require('path');
const server = require('http').createServer(app);
const io = require('../..')(server);
const port = process.env.PORT || 3000;
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
var store = new MongoDBStore(
{
uri: config.connectionString,
collection: 'tbl_session'
});
// Catch errors
store.on('error', function(error) {
socket.emit('mongodb-failed', error)
});
});
server.listen(port, () => {
console.log('Server listening at port %d', port);
});
// Routing
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
// when socket emits 'mongodb-connection-failed', this listens and executes
socket.on('mongodb-failed', (data) => {
// we tell the client to execute 'new message'
socket.broadcast.emit('mongodb-connection-failed', {
errorDetails: data
});
});
});
now at client side:
var socket = io();
socket.on('mongodb-connection-failed', () => {
console.log('you have been disconnected');
//do more whatever you want to.
});
This above example is using socket.io.
You can use any web socket library, see more here

Resources