简体   繁体   中英

Storing JSON POST data in an array (NodeJS)

I would like to be able to post user-generated JSON objects to a NodeJS server, and store them in an array so that refreshing the page does not affect the data. I would then like to be able to read the info back into a table, so that it constantly reflects the contents of the array.

Is this possible in NodeJS? If so, could someone please give me a pointer in the right direction? I'm able to pass JSON objects (as req.body), but I don't know where to go from here.

Thanks!

As Sri suggested, you should definitively store your data array into a data base. Use either Redis, Mongo, MySQL... It entierly depends on your data shape and the ways you will use it.

If you just neet to store temporary an array (by temporary, I mean "as long as the browsing session" or "as long as the server is up"), you can just store you data in memory.

For exemple with ExpressJs:

var express = require('express');
// in memory storage
var data = [];


var app = express()
  .use(express.bodyParser())
  .use(express.cookieParser())
  .use(express.cookieSession({secret:'sample'}))

  .post('/data', function(req, res){
    // do not need session, just memmory ? use this line
    // data.push(req.body);
    // creates the session if needed, and store data
    if (!req.session.data) {
      req.session.data = [];
    }
    req.session.data.push(req.body);
    res.send(204);
  })

  .get('/data', function(req, res){
    res.setHeader('Content-Type', 'application/json');
    // stored in session ?
    res.send(req.session.data || []);
    // stored in memory ?
    // res.send(data);
  })

  .listen(80);

----- EDIT -----

To add new data and return it in a single request, just send your array in the POST response:

  .post('/data', function(req, res){
    // store in memory
    data.push(req.body);
    // send it back, updated, in json
    res.setHeader('Content-Type', 'application/json');
    res.send(data);
  })

There is an assumption: you should call your post with an ajax call, and not a regular HTML form. Please refer to jquery.Ajax doc to get the parsed server result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM