Как сделать топор ios post или любой другой вызов API из Reactjs в бэкэнд Spring boot 2 - PullRequest
1 голос
/ 08 марта 2020

У меня есть API REST post для внутренней загрузки Spring boot 2: -

    @RequestMapping(value = "/profile", method = RequestMethod.POST)
public Profile saveOrUpdateProfile(@RequestParam("file") MultipartFile file, @RequestBody Profile profile, String path) {
    logger.info("file name:" + file.getOriginalFilename());
    if (file != null) {
        profile.setFileDownloadUri(profileService.storeFile(file, path));
        return profileService.saveOrUpdateProfile(profile);
    } else {
        return null;
    }
}

Я пытаюсь вызвать это из Reactjs следующим образом: -

  static postProfile(selectedFile, profile, replacePhotoPath) {
if (selectedFile) {
  let serverResponse;
  let formData = new FormData();
  formData.append("porofile", profile);
  formData.append("file", selectedFile);
  formData.append("path", replacePhotoPath);
  axios.post('http://localhost:8080/profile', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  .then(res => {
    console.log('res:' + res)
    serverResponse = res.data;
  })
  .catch((error) => {
    // handle this error
    console.log('error: ' + error);
    //setMessageFromServer(error.data)
   POST http://localhost:8080/profile 400 serverResponse = error.data;
  })
  return serverResponse;
}

}

Я получил сообщение об ошибке:

xhr. js: 178 POST http://localhost: 8080 / profile 415

Вы можете понять, что я пытаюсь опубликовать профиль с файлом фотографии. Я новичок в Reactjs и пытаюсь учиться кодированием. Я не знаю, как сделать этот топор ios после вызова этого API. Если это возможно сделать с помощью другого API, кроме ax ios, это нормально для меня Заранее спасибо!

Обновлены вопросы 1: - Конечная точка: -

    @RequestMapping(value = "/profile2", method = RequestMethod.POST, consumes = MULTIPART_FORM_DATA)
public ResponseEntity<?> saveProfile(@RequestParam("file") MultipartFile file, @RequestParam("path") String path, @RequestParam("profile") Profile profile) {
    logger.info("file name:" + file.getOriginalFilename());
    return null;
}

Reactjs: -

static postProfile(selectedFile, replacePhotoPath, profile) {
if (selectedFile) {
  let serverResponse;
  let formData = new FormData();
  formData.append("file", selectedFile);
  formData.append("path", replacePhotoPath);
  formData.append("profile", profile)
  axios.post('http://localhost:8080/profile', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  .then(res => {
    console.log('res:' + res)
    serverResponse = res.data;
  })
  .catch((error) => {
    // handle this error
    console.log('error: ' + error);
    //setMessageFromServer(error.data)
    serverResponse = error.data;
  })
  return serverResponse;
}
}

Я получил различную ошибку: -

POST http://localhost: 8080 / профиль 400

Обновленный вопрос 2: -

    @PostMapping("/profile2")
public void saveProfile(@ModelAttribute ProfileWrapper model) {
    logger.info("image: " + model.getImage());
    logger.info("profile: " + model.getProfile());
}

Reactjs: -

  static postData(selectedFile, replacePhotoPath, profile) {
if (selectedFile) {
  let serverResponse;
  let formData = new FormData();
  formData.append("porofile", profile);
  formData.append("file", selectedFile);
  formData.append("path", replacePhotoPath);
  axios.post('http://localhost:8080/profile', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  .then(res => {
    console.log('res:' + res)
    serverResponse = res.data;
    //this.postProfile(data, selectedCity, history);
  })
  .catch((error) => {
    // handle this error
    console.log('error: ' + error);
    //setMessageFromServer(error.data)
    serverResponse = error.data;
  })
  return serverResponse;
}

}

На этот раз, когда не было ошибок, он мог достичь конечной точки. Но члены модели ProfileWrapper не имеют значения. Таким образом, журнал напечатал: -

: изображение: ноль: профиль: ноль

Затем я обновил Reactjs как: -

  static postData(selectedFile, replacePhotoPath, profile, selectedCity, history) {
if (selectedFile) {
  let serverResponse;
  let wrappe = {
    "profile": profile,
    "image" : selectedFile,
    "path": replacePhotoPath 
  }
  // let formData = new FormData();
  // formData.append("porofile", profile);
  // formData.append("file", selectedFile);
  // formData.append("path", replacePhotoPath);
  axios.post('http://localhost:8080/profile', wrappe, {
    // headers: {
    //   'Content-Type': 'multipart/form-data'
    // }
  })
  .then(res => {
    console.log('res:' + res)
    serverResponse = res.data;
    //this.postProfile(data, selectedCity, history);
  })
  .catch((error) => {
    // handle this error
    console.log('error: ' + error);
    //setMessageFromServer(error.data)
    serverResponse = error.data;
  })
  return serverResponse;
}
}

То же самое снова нет ошибка, но она приходит в конечную точку с нулевым членом модели. Чтобы убедиться, я отлаживаю код внешнего интерфейса, чтобы убедиться, что я заполняю правильные данные, и они не равны нулю. Все выглядит хорошо.

Обновление 3: -

Кстати, я удалил элемент пути String как сзади, так и спереди.

public class ProfileWrapper {

private MultipartFile image;
private Profile profile;

public ProfileWrapper() {
}

public ProfileWrapper( MultipartFile image, Profile profile) {
    this.image = image;
    this.profile = profile;

}

public Profile getProfile() {
    return profile;
}

public void setProfile(Profile profile) {
    this.profile = profile;
}

public MultipartFile getImage() {
    return image;
}

public void setImage(MultipartFile image) {
    this.image = image;
}
}

Кстати, я обновил конечную точку до @RequestBody. Затем я получил эту ошибку: -

[dispatcherServlet]: Servlet.service () для сервлета [dispatcherServlet] в контексте с путем [[] выбросило исключение [Ошибка обработки запроса; вложенным исключением является org.springframework.http.converter.HttpMessageConversionException: ошибка определения типа: [простой тип, класс org.springframework.web.multipart.MultipartFile]; вложенное исключение: com.faster xml .jackson.databind.ex c .InvalidDefinitionException: невозможно создать экземпляр org.springframework.web.multipart.MultipartFile (не существует создателей, как, например, конструкция по умолчанию): абстрактные типы либо должны быть сопоставлены с конкретными типами, иметь собственный десериализатор или содержать дополнительную информацию о типе в [Source: (PushbackInputStream); строка: 1, столбец: 269] (через цепочку ссылок: com.profile.wrapper.ProfileWrapper ["image"])] с root причиной

com.faster xml .jackson.databind.ex c .InvalidDefinitionException: Невозможно создать экземпляр org.springframework.web.multipart.MultipartFile (создатели, такие как конструкция по умолчанию, не существуют): абстрактные типы либо должны быть сопоставлены с конкретными типами, иметь настраиваемый десериализатор, либо содержать дополнительную информацию о типе в [Source: (PushbackInputStream ); строка: 1, столбец: 269] (через цепочку ссылок: com.profile.wrapper.ProfileWrapper ["image"])

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