【问题标题】:angularjs$http.get and java api callangularjs$http.get 和 java api 调用
【发布时间】:2017-05-03 03:59:52
【问题描述】:

我正在尝试使用参数发出 angularjs $http.get 请求,但由于语法可能导致它无法正常工作。请你 确认我做错了什么,可能是angularjs调用或java api方法中的语法错误

$http.get(document.requestPathPrefix + "/home/my-api",
   $scope.requestParametersObject
   ).then(
        function(response) {
           $scope.output = response.data;
        },
        function(response) {
           $scope.retrieveErrorMssg = "Failed to retrieve required data.";
   });

我的参数和这张图片一样

parameter object for api call

在 java api 中像这样调用

@RequestMapping(value = "/my-api", method = RequestMethod.GET)
public ResponseEntity<Collection<MyObjectResponse>> getMyObjResponse(@RequestBody final MyObjectRequest request)
{
    Map<Integer,MyObjectResponse> oResponse = new HashMap<>();
    try {

        //Manipulation and db calls

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return new ResponseEntity<Collection<MyObjectResponse>>(oResponse.values(), HttpStatus.OK);
}

【问题讨论】:

  • 为什么你提出了一个 get 请求而不是创建一个 post 请求?
  • 据我了解,在这种情况下我可以同时使用 get 或 post

标签: javascript java angularjs rest


【解决方案1】:

试试,

$http({
                url: '/home/my-api',
                method: "GET",
                headers: {
                    'Content-type': 'application/json'
                },
                data: JSON.stringify(request)
            }).success(function(data, status, headers, config) {

            }).error(function(data, status, headers, config) {

                return null;
        });

【讨论】:

    【解决方案2】:

    如果您担心语法,请查看这个简单的示例并根据需要对其进行修改。

    在 JS 中,您的 http.get 调用应包含 URL 及其参数(如果有),

    $http.get('getUserInfo',
    {
       params : {
              'userEmail' : 'userEmail'
       }
    }).then(function(response) {
            console.log(response);
    });
    

    如果您将参数传递给 API 调用,请确保您的 Java 控制器或服务已定义为接收相同的参数。理想情况下,参数应该在调用和提供者之间匹配

    例如,对于上面的 API 调用,spring 控制器应该如下所示,

    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public @ResponseBody User getUserInfo(
            @RequestParam("userEmail") String userEmail) {
    // Do Something
    }
    

    【讨论】:

    • 我担心的不仅仅是语法,如果我正确地从 http.get 请求传递参数,我想有一些错误的格式,因为我的 java 调用没有被调用
    • 是的,因为您的参数应该与 http.get 调用匹配,我相信这不是您的情况
    • 还要确保 URL 是否完全匹配。在您的情况下,您在 API 映射之前添加了 /home。因此,当 URL 和参数匹配时,它应该触发 API
    • url 是正确的,但是 java 方法签名有问题,所以如果有任何想法请告诉我
    • 在您的 JS 中,我将其视为 /home/my-api,而在您的控制器中,我将其视为 /my-api。那么它正确吗? /home 是父级映射还是?
    猜你喜欢
    • 2015-05-22
    • 2016-03-29
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    相关资源
    最近更新 更多