NiTjSefni
NiTjSefni

Reputation: 85

How to save POST to global variable in node

I am sending json by POST to nodejs, I declared router.post in index.js, (/routes) How I can save it so I can actually use that later on? Keep in mind that every 60sec I am getting new data that should replace the old one.

I am listening on port 3000

var express = require('express');
var router = express.Router();
var saveme

/* GET home page. */
router.get('/index', function(req, res, next) {
  res.render('index', { title: 'RLH' });
});
router.post('/index', function(req, res, next) {
  data = req.body;
  console.log('OK')


});
module.exports = router;

I don't know how can I save what I get trough POST, so later on I can use it on my website.

Upvotes: 2

Views: 2528

Answers (2)

Sandeep Patel
Sandeep Patel

Reputation: 5148

There are multiple ways to use Global variable:

Method1

Using app.locals :

declare app.locals.data = {}; in main file (ex:server.js)

  var app = express();
  app.locals.data = {};

app.locals available to req object as req.app.locals. When you have new data you can update it as :

 req.app.locals.data = req.body;

Method2

Using global object

Assign new data as global.data = req.body

You can always access data as global.data in same or different module

Method3(Recommended)

Create file globaldata.js with below code

module.exports =  {};

Import globaldata.js where you need to access or update global data as

var globaldata = require('./globaldata.js');
globaldata = req.body;

What is recommended? global method for small apps, module.exports for big apps.

You can read below ref. for more details:

https://www.hacksparrow.com/nodejs/global-variables-in-node-js.html

http://expressjs.com/en/api.html#app.locals

Upvotes: 7

Robfz
Robfz

Reputation: 448

If by saving the data you mean storing it in a variable you can do:

var express = require('express');
var router = express.Router();
var saveme;

/* GET home page. */
router.get('/index', function(req, res, next) {
  if (saveme) {
     // you can use `saveme`
     res.render('index' + saveme.toString(), { title: 'RLH' });
  }
  else {
     res.render('index', { title: 'RLH' });
  }
});

router.post('/index', function(req, res, next) {
  data = req.body;
  // set `saveme`
  saveme = data;
});

module.exports = router;

Upvotes: 1

Related Questions