Connection is getting reset if I am doing a POST request

312 Views Asked by At

I am new to Node JS. Please help me to understand what am I doing wrong in the POST request. Sometimes my POST request is getting successfully resolved but sometimes it is giving me ECONNRESET.

I am sharing my app.js and file reader wrapper module.

GET is working perfectly fine.

Below is my App.js

const express = require('express');
const FileReader = require('./readFS');
const app = express();
const FS = new FileReader();

const port = 3000;
app.listen(3000, '127.0.0.1', () => {
  console.log(`App running on port ${port}`);
});
app.use(express.json());

app.get('/api/v1/tours', (request, response) => {
  const data = FS.read(`${__dirname}/dev-data/data/tours-simple.json`).then(
    (data) => {
      response.status(200).json({
        status: 'success',
        results: data.length,
        data: {
          tours: data,
        },
      });
    }
  );
});
app.post('/api/v1/tours', (request, response) => {
  (async (req, res) => {
    const tours = await FS.read(`${__dirname}/dev-data/data/tours-simple.json`);
    const newID = tours[tours.length - 1].id + 1;
    const newTour = Object.assign({ id: newID }, req.body);
    tours.push(newTour);
    console.log('File written Started');
    await FS.write(
      `${__dirname}/dev-data/data/tours-simple.json`,
      JSON.stringify(tours)
    );
    console.log('File written Successfully');
    res.status(200).send('Created Succesfully');
  })(request, response);
});

File Reader Module:


module.exports = class {
  constructor() {
    this.tours = [];
  }

  read(path) {
    return new Promise((resolve, reject) => {
      if (this.tours.length > 0) {
        resolve(this.tours);
      }
      fs.readFile(path, 'utf-8', (err, data) => {
        if (err) reject(er);
        this.tours = Object.assign(JSON.parse(data));
        resolve(this.tours);
      });
    });
  }
  write(path, data) {
    return new Promise((resolve, reject) => {
      if (data.length <= 0) reject('Data is empty');
      fs.writeFile(path, data, (err) => {
        if (err) reject('Could not write');
        resolve('Done');
      });
    });
  }
};
1

There are 1 best solutions below

2
user1071309 On

Explanation of the error I was encountering

My issue with occasionally receiving ECONNRESET when POSTing to my listening endpoint was caused by the endpoint automatically restarting after each successful POST of a file to that same endpoint.