Ответ отправлен 1 ответ поздно - PullRequest
0 голосов
/ 15 января 2019

Ответ, который я получаю от моего сервера Node.js, всегда на 1 ответ позже. Я всегда получу ответ, который должен был получить при нажатии кнопки «Загрузить».

Когда запускается сервер Node jus, ответ пуст. За последние четыре часа я пробовал множество вещей, и я не могу этого понять.

Я перешел с bodyParser на библиотеку с именем express-busboy для загрузки файлов, потому что мне не пришлось переписывать весь мой код. Все остальное в моем приложении все еще работает нормально, поэтому я начинаю думать, что проблема может быть связана с частью загрузки библиотеки из библиотеки.

Это мой код узла, извините, что это может быть немного утомительно читать, но я действительно потерян здесь, и это единственное, что мешает мне идти вперед.

Это код моего бэкэнда.

import * as fse from 'fs-extra';

export default class PhotoController{

  private postError = [];
  private postSuccess = [];

  public postPhotos =  (req, res) => {
    const fileArray = Array.isArray(req.files.file) ? req.files.file : new Array(req.files.file);
    const body = new Array(req.body);
    const item = body[0].item;
    const staticFileDest = `C:\\Users\\JP\\Desktop\\MiMApp\\MiMBackEnd\\movedUploads`;
     for (let i = 0; i < fileArray.length; i++){
      const removeDest = `./uploads/${fileArray[i].uuid}`;
      const newName =  Array.isArray(body[0].newName)? body[0].newName[i] : body[0].newName;
      const srcFile = `./${fileArray[i].file}`;
      const moveDest = `${staticFileDest}\\${item}\\${newName}`;
       fse.pathExists(moveDest)
        .then(exists => {
          if (exists){
          this.postError.push(`Fichier ${newName} existe deja.`);
          this.removeSrcFile(removeDest);
          } else {
            fse.move(srcFile, moveDest)
              .then( () => {
                const commentToAdd = Array.isArray(body[0].comment) ? body[0].comment[i] : body[0].comment;
                const commentPath = moveDest.replace(/\.[^/.]+$/, "").concat('.txt');
                this.postSuccess.push(`Fichier ${newName} à été ajouté dans l'item : ${item}`);
                this.removeSrcFile(removeDest);
                fse.writeFile(commentPath, commentToAdd)
                  .then(() => {this.postSuccess.push(`Le commentaire à été ajouté pour ${newName}`)})
                  .catch(() => {this.postError.push(`Le commentaire pour ${newName} existe deja.`)});
              })
              .catch(() => {
                this.postError.push(`Le fichier ${newName} n'a pas été rajouté correctement.`);
               this.removeSrcFile(removeDest);
               this.removeSrcFile(moveDest);
              });
           }
        });
     }
      this.sendResponse(res);
      this.resetErrors();
  };

  private removeSrcFile(file){
    fse.remove(file)
      .then(() => {})
      .catch(() => {this.postError.push(`${file} n'a pas pu être éffacé.`)});
  }

  private resetErrors(){
    this.postError = [];
    this.postSuccess = [];
  }

  private sendResponse(res){
    if (this.postError.length > 0){
      res.send({success : this.postSuccess, errors : this.postError});
    } else {
      res.send({success: this.postSuccess});
    }

  }

}

Внешний интерфейс:

onUpload()
  {
    const filesToUpload = new FormData();
    for (const values of this.selectedFile){
      filesToUpload.append('file', values.file);
      filesToUpload.append('newName', values.name);
      filesToUpload.append('comment', values.comment ? values.comment : 'Aucun commentaire.');
    }
    filesToUpload.append('item', this.itemNumber);
    this.photoService.postPictures(filesToUpload)
        .subscribe(
            res => {
              if (res){
                this.postResponse = res;
              } else {
                this.openUnexpectedModal();
              }
            },
            err => {
              this.openUnexpectedModal();
            },
            () => {
              this.openResponseModal();

            }
        )
  }

Сервис:

export class PhotoService {

    constructor(private http: HttpClient, private config: Config) {}

    public postPictures = (datas): Observable<any> => {
        return this.http.post(`${this.config.apiAddress}/postPictures`, datas)
            .pipe(
                map(data => {return data})
            );
    }
}

Первый ответ при отправке:

{"success":[]}

если я отправлю еще раз:

{"success":["Fichier 15012019-YEDwo.jpg à été ajouté dans l'item : 55","Le commentaire à été ajouté pour 15012019-YEDwo.jpg"]}

1 Ответ

0 голосов
/ 15 января 2019

Вы выполняете функцию asynchrounus, но ваша функция отправки this.sendResponse(res); запускается synchrounus.

 fse.move(srcFile, moveDest)
              .then( () => {
                ...
}

Это означает, что во время работы fse.move вы уже отправили запрос, а this.postSuccess был просто пустым массивом, инициализированным здесь private postSuccess = [];. Второй раз fse.move заканчивается, поэтому ваш ответ заполнен данными.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...