【问题标题】:My post method does not return data from the server after post我的 post 方法在 post 后没有从服务器返回数据
【发布时间】:2019-07-29 11:11:27
【问题描述】:

我有 POST 方法将数据发送到服务器,然后我想要返回数据。 当我订阅 post 方法时:

  this.categoryService.storeCategory(this.currentFileUpload, this.category).subscribe(category => {
      console.log("podaci" + category);

    }
    );

这是我在 Angular 中的 POST 方法:

 storeCategory(file: File, category: CategoryModel): Observable<HttpEvent<{}>> {
    const formdata: FormData = new FormData();
    console.log("1")
    formdata.append('file', file);
    formdata.append('category', new Blob([JSON.stringify({ "category_name": category.category_name, "category_description": category.category_description })], { type: "application/json" }))
    const url = `api/cateogry/saveCategory`;
    const req = new HttpRequest('POST', url, formdata, {
      reportProgress: true,
      responseType: 'text'
    });
    return this.http.request<CategoryModel[]>(req);
  }

这是我在 Spring Boot 中的 POST 方法:

@PostMapping(consumes = { "multipart/form-data" }, value = "/saveCategory")
    @ResponseStatus(HttpStatus.OK)
    public List<CategoryModel> createCategory(@RequestPart("category") @Valid CategoryModel category,
            @RequestPart("file") @Valid @NotNull MultipartFile file) {
        String fileName = fileStorageService.storeFile(file);

        String workingDir = System.getProperty("user.dir") + "/uploads/";

        category.setImage_path(workingDir + fileName);
        this.fileStorageService.storeFile(file);

        /*
         * String fileURL =
         * ServletUriComponentsBuilder.fromCurrentContextPath().path("/uploads/").path(
         * fileName) .toUriString();
         */

        this.categoryRepository.insertCategory(category.getCategory_description(), category.getImage_path(),
                category.getCategory_name());
        return this.categoryRepository.findAll();
    }

【问题讨论】:

    标签: angular spring-boot http


    【解决方案1】:

    @ResponseBody 在您的控制器 createCategory 方法中丢失。 @ResponseBody 注释告诉控制器返回的对象自动序列化为 JSON 并传递回 HttpResponse 对象。更多详情请查看this

    【讨论】:

      猜你喜欢
      • 2015-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      相关资源
      最近更新 更多