I am trying to learn use case of redis. As each tutorial is suggesting that it is better for caching a data.
I have made a simple demo where I am trying to connect with redis server in a web service get method.
var redis = require('redis');
var client = redis.createClient();
var express = require('express')
var app = express()
var port = process.env.PORT || 8080; // <== this is must
app.get('/fetch_offers', function (req, res) {
client.on('connect', function() {
console.log('connected');
});
});
app.listen(port, function () {
console.log(port)
})
I am trying to access it on localhost machine like http://localhost:8080/fetch_offers
I debugged it using console.log method but it does not print connected message. When I make this method outside the app.get... then it prints on executing node app.js.
I want it should make a redis connection on hitting a URL. I am not sure what is best way ? Can anyone help me ?
var redis = require('redis');
var client = redis.createClient();
var express = require('express')
var app = express()
var port = process.env.PORT || 8080; // <== this is must
client.on('connect', function() {
console.log('connected');
});
app.get('/fetch_offers', function (req, res) {
});
app.listen(port, function () {
console.log(port)
})
What wrong I am doing here ?
It doesn't print connection message because the event fires well before you hit the endpoint - at which point nothing is listening for it and it gets lost. Try something like this:
var redis = require('redis');
var client = redis.createClient();
client.on('connect', () => {
console.log('Redis connected');
});
client.on('ready', () => {
console.log('Redis ready');
});
client.on('error', (err) => {
console.log('Redis error:', err.message);
});
and then in your route handler you can use ping to see if you're connected:
app.get('/fetch_offers', function (req, res) {
client.ping((err, data) => {
if (err) {
console.log('Ping error:', err);
return;
}
console.log('Ping response:', data);
});
});
It would be slightly easier if you use promise-redis and async/await:
app.get('/fetch_offers', async (req, res) => {
try {
console.log('Ping response:', await client.ping());
} catch (err) {
console.log('Ping error:', err);
}
});
Related
I am building an API that uses socket connection to interact with a server backend built in C#. This is what I have so far
const request = require('request');
const express = require('express');
const app = express();
var server = require('http').createServer(app);
var cors = require("cors");
app.use(cors());
const net = require('net');
const client = new net.Socket();
const stringToJson=require('./stringToJson')
const port = process.env.PORT;
const host = process.env.HOST;
client.keepAlive=true
client.on('close', function() {
console.log('Connection closed');
});
app.get('/getScores',function (req,res) {
let dataSend=''
client.on('data', function (data) {
console.log('Server Says : ' + data);
if(data!='ANALYSIS-ERROR'){
dataSend=stringToJson.stringToJson(data)
}
else{
dataSend=stringToJson.stringToJson('0:0.0:0.0:0.0:0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0')
}
client.destroy()
return res.send(dataSend)
});
client.connect(port, host, function () {
client.write(`GENERAL-ANALYSIS|${req.query.id}|${req.query.website}|`)
return
});
return
})
app.get('/getPlace',function (req,res) {
console.log(req.query)
request(
{ url: `https://maps.googleapis.com/maps/api/place/textsearch/json?query=${req.query.name}+in+${req.query.city}&key=${process.env.API_KEY}` },
(error, response, body) => {
if (error || response.statusCode !== 200) {
return res.status(500).json({ type: 'error', message: error.message });
}
return res.json(JSON.parse(body));
}
)
})
//TODO ADD 404 500 PAGES
app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!");
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
server.listen(9000, () => {
console.log(`App running at http://localhost:9000`);
});
Basically it creates a connection with the server and listens for some data to be sent back. Then processes the string and sends it to the React frontend. The api calls are made by the frontend using axios
It works but if you refresh the page it throws this error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
How do I fix this?
Try setting the headers as found in the documentation request.setHeader(name, value)
request.setHeader('Content-Type', 'application/json');
guys, I'm trying to make simple TCP server with net.Socket package I'm using the express framework.
The behaviour that Im trying to achieve is when user enters specific route to emmit data to all connected clients, doesn anyone now how could I achieve this ??
Here is my sample code:
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const net = require('net');
const PORT = 5000;
let connection;
const server = net.createServer((socket) => {
console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
connection = socket;
});
app.use(cors());
app.use(bodyParser.json());
app.get('/', (request, response) => {
response.send('VMS server');
});
app.post('/contact', (req, res) => {
const data = { hello: 'hello' }
connection.write(data);
res.send({ data: 'data emmited' })
});
app.listen(PORT, () => {
console.log(`Server running at: http://localhost:${PORT}/`);
});
server.listen(1337, function() {
console.log("Listening on 1337");
});
The problem m having here is that data is gettings emitted multiple times, because Im assigning current socket to connection variable.
Is there any other way how I can do this, could I use server variable to emit to all connected clients somehow ?
Ok, managed to solve it. Here are steps on how I solved it - create an array of clients, & when a client connected to the server , push that socket to client array when disconnected remove that item from the array... And to emit data to all clients, I created a broadcast method where I loop through client array, and call the emit method of each socket & send data.
Here is a sample code:
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const net = require('net');
const PORT = 5000;
let sockets = []; // array of sockets
// emmit data to all connected clients
const broadcast = (msg) => {
//Loop through the active clients object
sockets.forEach((client) => {
client.write(msg);
});
};
const server = net.createServer((socket) => {
console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
sockets.push(socket);
socket.on('end', () => {
console.log('DISCONNECTED: ');
// remove the client for list
let index = sockets.indexOf(socket);
if (index !== -1) {
console.log(sockets.length);
sockets.splice(index, 1);
console.log(sockets.length);
}
});
});
app.use(cors());
app.use(bodyParser.json());
app.get('/', (request, response) => {
response.send('VMS server');
});
app.post('/contact', (req, res) => {
const data = { hello: 'hello' }
broadcast(data); //emit data to all clients
res.send({ data: 'data emmited' })
});
app.listen(PORT, () => {
console.log(`Server running at: http://localhost:${PORT}/`);
});
server.listen(1337, function() {
console.log("Listening on 1337");
});
I am developing an app that gets a signal from external hardware equipment. I catch this signal by redirecting it to a certain URL in my app: '/impulse/:id'.
I am able to catch the signal, but the emit function inside the app.get('/impulse/:id') is not triggering. The console logs are...
How can I make the emit function work?
Below is my server.js script, where I catch all the socket signals and prevent the external call from being redirected to the index page.
...
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;
const socket = require('socket.io');
app.use(express.static(__dirname + '/public'));
app.use('/api', appRoutes);
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://HERE IS MY DB INFO...', function(err) {
if (err) {
console.log('Not connected to the database: ' + err); // Log to console if unable to connect to database
} else {
console.log('Successfully connected to MongoDB'); // Log to console if able to connect to database
}
});
var server = app.listen(port, function() {
console.log('Running the server on port ' + port); // Listen on configured port
});
var io = socket(server);
io.on('connection', function(socket){
socket.on('join', function(data){
var gameroom = data.gameid;
console.log("joined: " + gameroom)
socket.join(gameroom);
})
//FUNCTION I WANT TO TRIGGER
socket.on('impulse', function(data){
console.log('IMPULSE')
io.emit('impulseReceived', {
})
})
})
//PLACE WHERE I EMIT
app.get('/impulse/:id', function(req, res){
console.log('Impulse Received')
var time = req.query.TIME;
var gameroom = req.params.id;
io.on('connect', function (socket) {
socket.emit('impulse', {
})
})
res.json({ success: true, message: 'received the time!'})
})
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/views/index.html')); // Set index.html as layout
});
Replace this whole
io.on('connect', function (socket) {
socket.emit('impulse', {
})
}
with this
io.emit('impulse', {})
I have an express server.
I set socket.setKeepAlive(true, 60000); in order to maintain persistent connection for at least 1min.
Here is the code:
var express = require("express");
var app = express();
var server = app.listen(8080);
app.get("/", (req, res) => {
res.write("Hello Riko");
});
// server.listen(3000);
server.on("connection", function(socket) {
console.log("A new connection was made by a client.");
socket.setKeepAlive(true, 60000);
socket.on("data", data => {
console.log(data);
});
// 30 second timeout. Change this as you see fit.
});
When the client send invalid request, it receives 400 Bad Request
How to prevent connection close on invalid request?
Yes the suggestion i made in the comments works.
server.on('clientError',cb) prevents the default behavior of the stack.
I encountered one problem though. It registers event listener for error event every time clientError is fired. Therefore I changed the code litle bit and ended up with a solution that works for me:
var express = require("express");
var app = express();
var server = app.listen(8080);
app.get("/", (req, res) => {
res.send("Hello Riko");
});
onSocketError = err => {
console.log("Socket Error: " + err);
};
server.on("connection", function(socket) {
socket.on("data", data => {
console.log(data.toString());
});
console.log("A new connection was made by a client.");
});
server.on("clientError", (err, socket) => {
socket.removeAllListeners("error");
});
Hope this would help someone with similar problem.
I've implemented a websockets api on top of a swagger-express node server.
For websockets I'm using express-ws which utilises the excellent ws library.
However I have come across a problem where the function setInterval is not being called when a websocket client connects.
Confusingly though in the ws.on('connection' function the console.log('websocket connected'); does execute while the setInterval function does not.
Can someone please point out what is wrong with my code?
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
module.exports = app; // for testing
var expressWs = require('express-ws')(app);
var IndexWS = require('./api/controllers/indexWS');
var config = {
appRoot: __dirname // required config
};
app.ws('/', function(ws, req) {
ws.on('connection', function(conn) {
console.log('websocket connected');
setInterval(function timeout() {
console.log('conn');
}, 500);
});
ws.on('close', function() {
console.log('The connection was closed!');
});
ws.on('error', function() {
console.log('websocket error!');
});
ws.on('message', function(msg) {
setTimeout(function timeout() {
ws.send("500 delay");
}, 500);
});
console.log('websocket connected');
});
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
var port = process.env.PORT || 3030;
app.listen(port, '0.0.0.0');
if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('server running on port ' + port );
}
});