Anthony
Anthony

Reputation: 979

Save data of POST request with Express

I'm trying to use the same API endpoint for GETTING and POSTING data to.

What I'm trying to do is the following:

  1. Make multiple POST request to /api/users, with the following data like: {'id': 2, is_valid: 'true'}
  2. So the data should be used later by fetching to this API URL and displaying it in my application.

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = 5000;

const jsonParser = bodyParser.json();


app.all('/api/users', jsonParser, (req, res) => {
    const users = [
        {id: '1', is_valid: false}
    ];

    users.push(req.body);

    res.json(users);
});

However, every time, I fetch this endpoint, it still only contains the original users array. The data I parsed and pushed to my array never got saved.

Upvotes: 0

Views: 740

Answers (1)

reactor
reactor

Reputation: 1931

have you tried moving

const users = [
    {id: '1', is_valid: false}
];

out of the callback (ie at least two lines above)?

Upvotes: 1

Related Questions