What is the best way to transmit a JSON object to REST services using Angular?

Whenever I attempt to send the JSON object to REST services, I encounter an error that looks like this:

http://localhost:8080/api/v1/cardLimit 400 (Bad Request);

JSON Object Example:

 public class GameLimit implements Serializable {

    private static final long serialVersionUID = 1L;

    private LimitType firstLimit;
    private LimitType secondLimit;

    public LimitType getFirstLimit() {
        return firstLimit;
    }

    public void setFirstLimit(LimitType firstLimit) {
        this.firstLimit = firstLimit;
    }

    public LimitType getSecondLimit() {
        return secondLimit;
    }

    public void setSecondLimit(LimitType secondLimit) {
        this.secondLimit = secondLimit;
    }
}


public class LimitType implements Serializable{

    private static final long serialVersionUID = 1L;

    private BigDecimal limit;
    private String type;
    private String status;

    public BigDecimal getLimit() {
        return limit;
    }

    public void setLimit(BigDecimal limit) {
        this.limit = limit;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

Request Object for Limits:

public class LimitReq extends GameLimit {

    private String key;

    public String getKey() {
        return key;
    }
}

RestController Setup:

@RequestMapping(value = "/GameLimit", method = RequestMethod.POST)
    public Response setCardLimit(@RequestBody GameLimitReq request) throws Exception {
        return limitService.updateGameLimit(request);
    }

TypeScript Client Implementation:

changeLimits(firstLimit: IWidgetLimit, secondLimit: IWidgetLimit, key: string): ng.IPromise<any> {
            return this.$http.post(this.apiPrefix + '/GameLimit', {
                'firstLimit': {
                    limit: firstLimit.limit,
                    type: firstLimit.type,
                    status: firstLimit.status
                },
                'secondLimit': {
                    limit: secondLimit.limit,
                    type: secondLimit.type,
                    status: secondLimit.status,
                },

                key: key
            }).then(function (response: any) {
                return response.data;
            }.bind(this));
        }

Answer №1

After reading through this question and its corresponding answer, it becomes clear that a 400 error indicates issues with the structure of your JSON data.

Upon reviewing your code snippets, it appears that the line

limitService.updateGameLimit(request);
should be generating the JSON output. However, this crucial part is missing from the provided code snippets. Once you have access to the result of that method, I recommend running it through JsonLint to verify the syntax before proceeding with any necessary corrections.

Based on the TypeScript client information provided, it seems like there might be some invalid JSON being supplied. While I may not be deeply knowledgeable in TypeScript, it's evident that there are potential issues with the JSON formatting, such as missing double quotes around certain key values like firstLimit, secondLimit, and key.

Answer №2

The issue lies in the incorrect formation of your json data. There are various reasons contributing to this problem.

  1. Your keys must be enclosed in quotes as strings. For example, use "type" instead of type.
  2. You mistakenly added a comma at the end of a line

    status: secondLimit.status,
    

    Please remove the unnecessary comma.

Once rectified, validate your output on jsonlint.com or a similar platform to pinpoint any remaining mistakes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular's GET request response is returning an "Undefined" value instead of the

As an Angular beginner, I've successfully set up and tested a service that retrieves data from a JSON file using the Get method. However, when attempting to access the data inside the JSON file, it returns as undefined. My goal is to use this data as ...

Issues encountered when executing unit tests using karma

I encountered these issues in the logs. Seeking advice on how to proceed. Thank you. I've attempted uninstalling and reinstalling phantomjs, clearing out my node modules and bower component directories. Everything was functioning as expected before, a ...

[AWS Lambda SDK] - Executing Lambda Function - Processing Payload Response as Unit8Array - Conversion to String

Currently, I am utilizing the npm package @aws-sdk/client-lambda to invoke Lambdas. In my setup, I have two Lambdas - Lambda A and Lambda B, with Lambda A responsible for invoking Lambda B. The invocation of Lambda B from Lambda A is done through the foll ...

angular trustAsHtml does not automatically insert content

Two divs are present on the page. Upon clicking button1, an iframe is loaded into div1. The same applies to button2 and div2. These iframes are loaded via ajax and trusted using $sce.trustAsHtml. This is how the HTML looks: <div ng-bind-html="video.tru ...

Tips for navigating the material ui Expanded attribute within the Expansion Panel

After looking at the image provided through this link: https://i.stack.imgur.com/kvELU.png I was faced with the task of making the expansion panel, specifically when it is active, take up 100% of its current Div space. While setting height: 100% did achi ...

Stop repeated form submissions in Angular using exhaust map

How can we best utilize exhaust Matp to prevent multiple submissions, particularly when a user is spamming the SAVE button? In the example provided in the code snippet below, how do we ensure that only one submission occurs at a time even if the user click ...

What is the proper way to structure a URL in JSON output?

When utilizing JSON output in my project, I encountered the following result: {"short_url":"http:\/\/urlhere\/fb\/37xzk"} However, the desired output should be formatted as follows: { "short_url":"http: //urlhere/fb/37xzk" } ...

Remove dynamically created elements from an AngularJS div

Is there a way to remove an item from the criteria list when clicking the delete button? Currently, only the filter is being refreshed and not the tables. Any suggestions on how to resolve this issue? HTML <ul class="list-unstyled"> <l ...

Leveraging ng-repeat with multiple arrays

I'm currently developing a weather application, but I've hit a roadblock when trying to tackle what I thought would be a simple task. Unfortunately, my limited experience with Angular has made it difficult for me to figure out how to achieve this ...

Leverage elements from nearby npm repository when building an Angular 2 application

After developing a generic chart component using d3 and Angular 2, I decided to share it by publishing it in a local npm repository. This way, anyone can easily incorporate the chart component into their Angular project by simply running the npm install my ...

Parsing JSON data using Swift

I need assistance with making an API call to the GitHub API in order to retrieve the names of folders within a repository. I'm unsure about how to extract and process the data returned from the API call. Any guidance or help on this matter would be gr ...

What is the best way to output data to the console from an observable subscription?

I was working with a simple function that is part of a service and returns an observable containing an object: private someData; getDataStream(): Observable<any> { return Observable.of(this.someData); } I decided to subscribe to this funct ...

Determining the data type of an object key in Typescript

Is there a way to limit the indexed access type to only return the type of the key specified? interface User { id: string, name: string, age: number, token: string | null, } interface Updates<Schema> { set: Partial<Record< ...

Setting up Tarui app to access configuration data

I am looking to save a Tauri app's user configuration in an external file. The TypeScript front end accomplishes this by: import {appConfigDir} from "tauri-apps/api/path"; ... await fetch(`${await appConfigDir()}symbol-sets.json`) { ... ...

JSON Date Format

I'm facing an issue where I am unable to retrieve the current date using new Date() because it is in JSON format. This particular code was written using MVC C#. The date appears as \/Date(1531364413000)\/. The dates stored in the database ...

What is the best way to send information from ng-repeat items in one view to another view when both views are controlled by a single controller?

There are two views (2 html templates) that share a common controller. In view 1, which contains ng-repeat items, For example: In "view 1": ng-repeat = "monthid in years" It displays: month 1, month 2, ... month 12 Now I want to click on "mo ...

Ionic retrieves a filtered array of JSON data

Having difficulty filtering the array to retrieve values where the parent id matches the id that is provided. For instance, if an ID of 1 is sent, it should result in a new array with 3 items. An ID of 4 will return 1 item, and an ID of 5 will also return ...

The Gson library fails to properly format a singular variable extracted from a JSON string

I am currently facing an issue with converting a json format, which is an arraylist response from a rest webservice, into its corresponding java arraylist. Interestingly, out of the 3 variables in the json response, only 2 are successfully formatted into ...

Utilizing TypeScript namespaced classes as external modules in Node.js: A step-by-step guide

My current dilemma involves using namespaced TypeScript classes as external modules in Node.js. Many suggest that it simply can't be done and advise against using namespaces altogether. However, our extensive codebase is structured using namespaces, ...

Is it possible to implement the same technique across various child controllers in AngularJS?

I am trying to execute a function in a specific child controller. The function has the same name across all child controllers. My question is how can I call this function from a particular controller? Parent Controller: app.controller("parentctrl",functi ...