Yasir Shahzad
Yasir Shahzad

Reputation: 57

Problem in Middlewares, cannot post to /api/upload

I am working on a small import system. User upload the file from frontend and Nodejs handle that file and parse data from csv and insert in db.

I have different middleware to handle the request. I want to first authorize the user, secondly upload the data and extract the data to req.data and in last I want to send response with completion of request.

app.post('/api/upload', auth, upload.single("file"),  (req, res, next) =>{
    let steam = fs.ReadStream(req.file.path); 
    csvtojson()
    .fromStream(steam)
    .then( function(data){
      req.data = data; 
    });
    next(); 
}, doImport);

these are middlewares:

function auth(req, res, next) {
      console.log("Authorizing"); 
       next(); 
}

function doImport(req, res, next){
       console.log("importing Data"); 
       console.log(req.data);    
        res.send(req.data); 
}

The error is:

   []

Empty Array

Upvotes: 0

Views: 89

Answers (1)

Will Alexander
Will Alexander

Reputation: 3571

You are currently attempting to call next() before req.data is populated, so your middleware is sending the empty array. Remember that if you need to be certain that a line gets run after an asynchronous action is completed, you need to put that line in the appropriate place (inside the .then() block in this case):

app.post('/api/upload', auth, upload.single("file"),  (req, res, next) =>{
  let steam = fs.ReadStream(req.file.path); 
  csvtojson()
  .fromStream(steam)
  .then( function(data){
    req.data = data; 
    next() //
  }).catch(err => next(err)); 
}, doImport);

As shown, you should also handle errors, because if you don't and an error is thrown, your request will time out (no call to next()).

Upvotes: 1

Related Questions