0

AngularJS Client Side:

userTab.factory('someService', ['apiService','$rootScope', function(apiService, $rootScope){
    return {
        updateData : function (someObj){
            return apiService.request({
                apiMethod: 'user/v1/updateData',
                httpMethod: 'POST',
                fileData: JSON.stringify(someObj)
            }).error(function(data, status) {
                throw "updateData error: " + status;
            });
        }
    }
}]);

Server Side Code:

Update.java

@Controller("user")
@RequestMapping(value = "/user/v1")
public interface Update
{
    @ResponseBody
    @ResponseStatus(HttpStatus.CREATED)
    @RequestMapping(value = "/users/{username}/updateData", method = POST)
    String updateData(HttpServletRequest request, HttpServletResponse response, @PathVariable("username") String username, @RequestBody UserUpdate userUpdate);
}

UpdateImpl.java

@Override
@Transactional
public String updateData(HttpServletRequest request, HttpServletResponse response, @PathVariable("username") String username,
        @RequestBody UserUpdate userUpdate) {

        String requestBody = ServletUtils.getRequestBody(request);
        logger.info("RequestBody: "+requestBody);

        return new String("true");
}

Response: RequestBody: {}

So as you see that RequestBody is coming as blank as I haven't given anything in params within angularjs API call.

So how to get the fileData which is not in params here?

UPDATE:

My fileData is a normal json array just like this:

{
  "todo" : "Dinner",
  "user" : [
    {
      "name" : "username",
      "password" : "passwordabc"
    }
  ],
  "notes : "some notes"
}

And I have created it in an angularjs as follows:

var object = {};
object.todo = "Dinner";
object.notes = "some notes";
userArray = [{
                name: 'myname',
                password: 'password'
            }];
object.user = userArray

UPDATE:

apiService.js

'use strict'; 

apiModule.factory('apiService', ['$http', '$q', 'LoginService','XSSValidator', function($http, $q, loginService, XSSValidator) {
    var basePath="https://somesite.com/userApi/";
    var _httpMethod="POST";
    var caching=false;
    var latestRequest={};
    $http.defaults.withCredentials = true;

    return{

    if(typeof bundle.fileData != "undefined"){
                return $http({
                    cache: caching,
                    method: bundle.httpMethod,
                    headers:{"Content-Type":contentType},
                    url:basePath+bundle.apiMethod, 
                    data:dataStr,
                    transformRequest: angular.identity,
                    transformResponse:bundle.transformResponse,
                    timeout: canceller.promise
                }).success(function(data, status, headers, config) {
                    //check to see if request has been redirected to login page, suggesting user has been logged out
                    if(typeof data==='string' && data.substr(0,44)==='<html><head><title>Login Page</title></head>'){
                        window.location.href="/login" + window.location.search;
                    }

                    var req;
                    if(config.data !== ""){
                        var requestArr=config.url.split(config.data);
                        req=requestArr[0].split("?")[0];
                    }
                    else{
                        req=config.url;
                    }
                    if(config.data !== "" && !data.fault){
                        if(Object.prototype.toString.call(data) == "[object String]"){
                            var msg = XSSValidator.validate("Response ", data);
                            if (msg != null) {
                                return $q.reject({ message: msg });
                            }
                        }else if(config.headers["Content-Type"] == "application/x-www-form-urlencoded" || config.headers["Content-Type"] == "application/json"){
                            eval(data);
                        }
                    }
                    if(latestRequest[req]!==config.url){
                        //cancel promise 
                        return $q.reject({ message: 'Rejecting this promise' });
                    }
                }).error(function(data, status, headers, config) {
                    if(status===401){ //user has been logged out server-side. redirect to login pg
                        window.location.href="/login" + window.location.search;
                    }
                    // called asynchronously if an error occurs
                    // or server returns response with an error status.
                });
            }
sjain
  • 23,126
  • 28
  • 107
  • 185
  • 1. You haven't added request mapping. 2. You are not returning anythign 3. You don't have response body annotation ("if not using `@RestController`") 4. you haven't specified request type – Pragnani Feb 24 '16 at 10:40
  • I will update shortly if that matters here. Actually the code I posted is the implementation of the interface which contains all that you said. – sjain Feb 24 '16 at 10:41
  • is your fileData a normal json String or any multipart file ? – Pragnani Feb 24 '16 at 11:02
  • Its a normal json. Please see my update for clear idea. – sjain Feb 24 '16 at 11:08
  • What does `apiService.request` do? If it uses the `$http` service, then it should probably be `fileData: someObj`. But as it doesn't seem to send anything at all, I guess `fileData` is not the property to use in this case. – a better oliver Feb 24 '16 at 11:28
  • is ApiService is your utility js function to make api requests ? please post that, because we really don't how you make a call. We generally supply request body in 'data' param in the function. I am not sure if it helps try changing 'fileData' param name to 'data' because receiver function may not interpret that param because it may not have a idea about its name – Pragnani Feb 24 '16 at 11:32
  • apiService.js file is too long. I have only posted the relevant code of this file. Please have a look. – sjain Feb 24 '16 at 13:00
  • What does ServletUtils.getRequestBody() do? Why don't you simply use userUpdate, which contains the unmarshalled request body already? – JB Nizet Feb 24 '16 at 13:13
  • @JBNizet - I got the json from your hint. At server side, I used userUpdate like this `JSONObject jsonObject = new JSONObject(userUpdate );`. And then I passed it to the method as jsonObject.toString(). Thank you. – sjain Feb 24 '16 at 15:42

0 Answers0