简体   繁体   English

获取响应时发生错误,如果nodejs服务器在某些延迟后发送响应

[英]error in getting the response, if nodejs server send response after some delay

I am trying to upload the image, and then nodeJS server send the path of that image folder back as a response. 我正在尝试上传图像,然后nodeJS服务器将该图像文件夹的路径发送回作为响应。

But When I sending the response after performing some task, nothing happening on angular-side. 但是当我在执行某些任务后发送响应时,在角度侧没有任何反应。

this is my component.ts file. 这是我的component.ts文件。

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 和我的service.ts

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

and my app.js 和我的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. 请有人帮我。

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. 如果异步方法中有错误,则必须将其传递给next()函数,以便express可以处理它。

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 });
    }
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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