0

I am trying to upload the image, and then nodeJS server send the path of that image folder back as a response.

But When I sending the response after performing some task, nothing happening on angular-side.

this is my component.ts file.

uploadImage() {
    const formData = new FormData();
    formData.append('photo', this.image);
    const obj$ = this.userService.uploadData(formData); 
    obj$.subscribe(data => {
      console.log(data);   //// nothing happening.
      if (data.success) {
        this.uploadForm.patchValue({
          document: data.url
        });
      }
    });
  }

and my service.ts

uploadData (uploadImage) {
   return this.http.post<UploadPhoto>('/user/upload', uploadImage);
  }

and my app.js

router.post('/upload' ,upload.single('photo'), (req,res) => {

  console.log(req.file);
  const body = req.file;

  cloudinary.uploader.upload(body.path, (err, result) => {
    if (err) {
      console.log(err);
      return;
    }
    console.log(result);
    res.status(200).json({
      url: result.url,
      success: true
    });
  });
});

But when I am sending response without performing any task, it works fine like

router.post('/upload' ,upload.single('photo'), (req,res) => {

  console.log(req.file);
  const body = req.file;

  res.status(200).json({
       url: 'hello',
       success: true
  })

});

I don't know why is this happening.

Please someone help me.

Daniel Gimenez
  • 18,530
  • 3
  • 50
  • 70
  • 1
    Very likely a dupe of https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – mplungjan Aug 14 '18 at 15:04
  • Try to pu a breakpoint inside the callback of `cloudinary.uploader.upload()`, and see if you get there, if there are errors. – Chayim Friedman Aug 14 '18 at 15:09
  • Thanx for you help. it produces an error that's why it is not sending the response properly. Now I have corrected that. – Rupesh yadav Aug 14 '18 at 15:52

1 Answers1

1

When an error occurs in your uploader you're returning the error to the console and then ending execution. If there is an error in the asynchronous method you must pass it to the next() function so that express can handle it.

router.post('/upload' ,upload.single('photo'), (req,res, next) => {

  console.log(req.file);
  const body = req.file;

  cloudinary.uploader.upload(body.path, (err, result) => {
    if (err) {
      console.log(err);
      next(err);
    }
    else {
      console.log(result);
      res.status(200).json({ url: result.url, success: true });
    }
  });
});
Daniel Gimenez
  • 18,530
  • 3
  • 50
  • 70