Node-Cache data won't persist. Clears when page connection reset - javascript

I made this simple example to see how to use the node-cache module. But if I disconnect from node and reconnect the cache gets cleared. Is there a way to make sure the data persists until I clear it? My code is below, thanks for your help.
const express = require('express');
const app = express();
const port = process.env.port || 3000
const NodeCache = require( "node-cache" );
const myCache = new NodeCache();
app.listen(port, (err :boolean)=> {
if (err){
return console.log(err);
}
return console.log(`server is listening on ${port}`);
})
app.get('/', (req, res)=>{
console.log(req.originalUrl);
res.send('I am trying');
})
app.get('/add/:input/:value', (req,res)=>{
let i = req.params.input;
let v = req.params.value;
const success = myCache.set(i, v);
console.log(success);
res.send(`key: ${i} value: ${v}`);
})
app.get('/loop', (req,res)=>{
let mykeys = myCache.keys();
res.send(mykeys);
})

Related

Express, function is only executed once

I'm recently doing tests with the venom-bot library for whatsapp, but when executing the "action" action in my browser, it only runs once, after that it doesn't send a message to any number! I can't find where I'm going wrong.
const express = require('express');
const venom = require('venom-bot');
const bodyParser = require('body-parser');
venom
.create({
session: 'randomsession', //name of session
multidevice: true // for version not multidevice use false.(default: true)
})
.then((client) => start(client))
.catch((erro) => {
console.log(erro);
});
async function start(client) {
const app = express();
const PORT = 3333;
app.use(bodyParser.json())
app.get("/enviarcode", async (req, res, next) => {
await client.sendText(req.query.number + "#c.us", req.query.message);
res.json(req.query);
})
app.listen(PORT, () => {
console.log(`Online on Port ${PORT}`)
})
}

Put request req.body is empty

As all my requests are working fine, I have a problem with the put. req.body stays empty and then gives that error :
errmsg: "'$set' is empty. You must specify a field like so: {$set:
{: ...}}"
PUT :
router.put('/books/:name', (req, res, next) => {
const localdb = db.client.db(process.env.DB_NAME);
const collection = localdb.collection(process.env.COLL_BOOKS);
collection.replaceOne(
{ "name": req.params.name },
{ $set: req.body },
function (err) {
if (err) throw err
res.status(201).send(true);
});
App.js
const express = require('express'),
app = express();
os = require('os');
const bodyParser = require('body-parser');
const cors = require('cors');
const router = require('./router.js')
require('dotenv').config()
app.use(cors());
app.use(bodyParser.json());
app.use('/api/v1', router);
const port = (process.env.PORT || '3001');
let server = app.listen(port, os.hostname(), () => {
let host = server.address().address,
port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
axios request :
updateItem = newBook => {
Axios.put(process.env.REACT_APP_API_PATH_BOOKS + `${newBook.name}`, newBook)
.then(res => {
this.setState({ newBook: res.data });
this.props.history.push('/admin');
})
.catch(err => console.log(err));
}
I don't understand what I am doing wrong
Make sure you don't have any middlware stripping or incorrectly parsing the body. For instance, you may have a JSON body parser, and not be sending JSON data with JSON application headers.
Can you give a bit of context, in code, for how you are making the put request and also the result of logging the req in a pastebin?

How to save a variable before serving a file in nodejs

given the following code:
const https = require('https');
const fs = require('fs');
var path = require('path');
const express = require('express');
const app = express();
const router = express.Router();
const pool = require('./mysqldb.js');
const pathView = __dirname + "/views/";
const IMGPath = "/public";
var bodyParser = require("body-parser");
const listenPort = 8010;
var id = null ;
router.get('/details/:id', async function (req, res, next) {
id = req.params.id;
if ( typeof req.params.id === "number"){id = parseInt(id);}
res.render('details.ejs' );
});
The main goal is to save that req.params.id(the id from the url) in the id variable before serving the details.ejs file.I tried to remove the async but didn't work.Can you help me please?
You can make use of the await keywords inside your async function like so:
router.get('/details/:id', async function (req, res, next) {
await (() => { id = req.params.id; })(); // Will run first
await (() => { res.send(id); })(); // Will run second
})
res.send(id) or res.render('details.ejs') ( in your case ) will run after the id is retrieved
It seems to be working fine for me. Below, I launch this server, then I go to http://localhost:3050/123 and suddenly I'm console.logging '123' over and over again, and the correct text displays on the screen.
So... idk what else if going on for you, but it might help if you try your best to distill your code down to the simplest possible iteration to try to debug. Just try to replicate it elsewhere. You might find one of your additional modules is causing an issue.
const express = require('express')
const app = express();
const port = 3050;
let id = null;
app.get('/:id', (req, res) => {
return res.send('Hello World!')
});
app.get('/details/:id', (req, res) => {
if (req.params.id){
id = req.params.id;
}
// 'id' will appear in browser
return res.send(`See details for id: ${id}`);
});
// console logs of 'id'
setInterval(() => { console.log(`id is currently ${id}`); }, 1000);
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
I don't think async/await will have any effect on this specific issue. I doubt they're related.
This seems to work for me,
router.get('/details/:id', async function (req, res, next) {
id = typeof req.params.id === 'number' ? parseInt(id) : req.params.id;
console.log(id);
res.send('details.ejs' );
});

Error: Connection lost: The server closed the connection. mysql node

I have seen many solutions to this problem in google, but I could not apply them. API works well, but after some time this error appears.
...................................................................................................................................................................................................................................................................
index.js
const express = require('express');
const app = express();
const router = express.Router();
const path = require('path');
const habalka = require('./routes/habalka')(router);
const port = process.env.PORT || 3000;
app.use('/api/habalka', habalka);
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
db.js
const mysql = require('mysql');
const db_config = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'habalka'
});
db_config.connect(function(err) {
if (err) {
console.log('error when connecting to db:', err);
}
});
module.exports = db_config;
habalka.js
const connect = require('../db');
module.exports = (router) => {
router.get('/get', (req, res) => {
let sql = 'SELECT * FROM test';
connect.query(sql, (err, results) => {
if (err) throw err;
res.json(results);
});
});
return router;
};
I would suggest using Sequelize ORM. It abstracts away writing raw SQL and it is much safer.

Calling methods from other files with Node.js

I'm failing to require methods from my ./db/index.js into my server.js file to select data from the database and display it.
The /db/index.js is like this:
'use strict';
const pgp = require('pg-promise')();
const pg = pgp(process.env.DATABASE_URL);
let select = () => {
pg.any('SELECT username, status FROM status')
.then(function(data){
for (var item of data) {
return item.username + "'s status is " + item.status;
}
})
.catch(function(err) {
return 'Error: ' + err.message || err;
});
};
module.exports = () => {
select
};
and I want to call it in from a different file:
'use strict';
const port = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const db = require('./db/');
app.use(bodyParser.urlencoded({extended: true}));
app.post('/logdash', function(req, res, next) {
res.status(200).send(db.select());
});
app.listen(port, function() {
console.log('Server is running on port', port);
});
I'm using Heroku, and like this, watching the logs, no error is shown in both terminal and Slack (it's a slash command). I can't find help on how to properly separate the functions. How can I call this select method and any other one from a different file?
There are many problems in your code, some of them listed in the previous answer by #jfriend00.
I will only add that you also do not return any data from the method when it is successful.
Considering how many errors you got there, rather than re-iterating them, I will give you a corrected code example instead.
The database module:
'use strict';
const pgp = require('pg-promise')();
const db = pgp(process.env.DATABASE_URL);
let select = (req, res, next) =>
db.map('SELECT username, status FROM status', null, row=> {
return row.username + "'s status is " + row.status;
})
.then(data=> {
res.status(200).send(data);
})
.catch(err=> {
res.status(500).send(err.message || err);
});
module.exports = {
select
};
And the HTTP service file:
'use strict';
const port = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const db = require('./db/');
app.use(bodyParser.urlencoded({extended: true}));
app.post('/logdash', db.select);
app.listen(port, function () {
console.log('Server is running on port', port);
});
The code is based on pg-promise v.4.3.x (upgrade, if you have an older one).
I wouldn't say it is a good approach to organizing your code, but at least it is a working example. You can check out pg-promise-demo for a complete application example that may give you a better idea of how to organize your database code.
API references: map
The code in your module is asynchronous. You can't return a value directly. Instead, you should return the promise and then use the promise from the caller to obtain the final asynchronous value.
For further discussion of this general concept see this answer:
How do I return the response from an asynchronous call?
Change your code to this (see embedded comments):
'use strict';
const pgp = require('pg-promise')();
const pg = pgp(process.env.DATABASE_URL);
let select = () => {
// return the promise here
return pg.any('SELECT username, status FROM status')
.then(function(data){
return data.map(function(item) {
return item.username + "'s status is " + item.status;
});
})
.catch(function(err) {
// to keep this an error, we have to rethrow the error, otherwise
// the rejection is considered "handled" and is not an error
throw 'Error: ' + err.message || err;
});
};
// export the function
module.exports.select = select;
And call it like this:
'use strict';
const port = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const db = require('./db/');
app.use(bodyParser.urlencoded({extended: true}));
app.post('/logdash', function(req, res, next) {
db.select().then(function(data) {
res.status(200).json(data);
}).catch(function(err) {
// add some sort of error response here
res.status(500).json(err);
});
});
app.listen(port, function() {
console.log('Server is running on port', port);
});
Summary of changes here:
In select(), return the promise
In the .catch() in select(), rethrow the error to keep it a rejected promise. If you add a handler for a .catch() and don't either rethrow or return a rejected promise, then the error is handled and the promise becomes resolved.
You need to fix your for loop. It should not be doing a return inside the for loop with no conditional checks. That code is probably just wrong (though I'm not sure what you intended to do).
When you call db.select(), use a .then() handler to get teh final resolved value.
Add an error handler for the db.select() promise.
Change the exports so that db.select() is your function.
Revised the way you were referencing data in the for loop so it will actually fetch the desired property.
A few things. I would make sure that your select function returns a Promise. I would also handle the promise in your route. This way you can properly send the appropriate status codes and responses.
db/index.js
'use strict';
const pgp = require('pg-promise')();
const pg = pgp(process.env.DATABASE_URL);
let select = () => {
return pg.any('SELECT username, status FROM status')
}
module.exports = () => {
select
};
server.js
'use strict';
const port = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const db = require('./db/');
app.use(bodyParser.urlencoded({extended: true}));
app.post('/logdash', function(req, res, next) {
db.select()
.then((data) => {
res.status(200).json(data)
})
.catch((error) => {
res.status(500).json(error)
})
});
app.listen(port, function() {
console.log('Server is running on port', port);
});
I did not test this, but it should do the trick.

Categories