【问题标题】:Angular 4 http post to Java SpringMVC; POST parameters not seenAngular 4 http 发布到 Java SpringMVC;未看到 POST 参数
【发布时间】:2017-10-02 21:25:48
【问题描述】:

我正在开发 Java Maven Spring 启动 SpringMVC 中的 REST api。 SpringMVC @RequestParam 看不到 Angular POST 请求参数。这是 Angular 代码;

  saveAsSiteProduct(id: number, data: saveAsSiteProductSettings): Observable<any> {
    const options = new RequestOptions({ headers: new Headers({ 'Content-Type': 'application/json' }) });
    return this.http
      .post(this.amazonUrl + '/products/imported/' + id +'/saveas/siteproduct', JSON.stringify(data), options)
      .map(response => response.json());
  }

这里是 Java SpringMVC 代码;

@PostMapping(value = "/products/imported/{id}/saveas/siteproduct", produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody ResponseEntity<CustomHttpResponse> saveAsSiteProduct(
            @PathVariable Long id,
            @RequestParam Map<String, String> requestParams,
            @RequestParam("guid") String guid
            ) throws EncoderException, RestClientException {
...
}

但我收到了回复;

{
    "timestamp": "2017-10-02T21:21:58.064+0000",
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.bind.MissingServletRequestParameterException",
    "message": "Required String parameter 'guid' is not present",
    "path": "/api/amazon/products/imported/1/saveas/siteproduct"
}

这就是我要发布的内容;

{
createBrandIfNotExists : true
createManufacturerIfNotExists : true
guid : "asD"
}

我已经在 Postman 中对此进行了测试,并且可以正常工作。

【问题讨论】:

    标签: javascript java ajax angular spring-mvc


    【解决方案1】:

    我改用URLSearchParams 并将Content-Type 更改为application/x-www-form-urlencoded。这是我的做法;

      saveAsSiteProduct(id: number, data: saveAsSiteProductSettings): Observable<any> {
        const options = new RequestOptions({ headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }) });
        const params = new URLSearchParams();
        for (var key in data) {
          params.set(key, data[key]);
        }
        return this.http
          .post(this.amazonUrl + '/products/imported/' + id +'/saveas/siteproduct', params, options)
          .map(response => response.json());
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-23
      • 2011-11-14
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 2017-07-09
      • 1970-01-01
      相关资源
      最近更新 更多