Angular Sending JSON Data via POST Request

Whenever I submit an empty form through my Angular application, the JSON being sent is as follows:

{foo: {}}

This causes a 500 error to occur on my server instead of the expected 422 error, since the server requires the following structure:

{foo: {bar: ""}}

Is there a way to ensure that the "bar" key is always present in the JSON even if its value is empty?

Below is the current state of my controller:

$scope.baz = {};
$scope.create = function() {
    var error, success;
    $scope.errors = {};
    success = function() {
      $scope.baz = {};
    };    
    error = function(result) {
        angular.forEach(result.data.errors, function(errors, field) {
            $scope.form[field].$setValidity('server', false);
            $scope.errors[field] = errors.join(', ');
        });    
    };

    Foo.save({ foo: { bar: $scope.baz.bar }}).$promise.then(success, error);

};

Answer №1

It seems that when passing an undefined object property in the save request, it may be ignored or removed before being sent to the server. To prevent this from happening, you can assign an empty string value to ensure it is included in the request object. You can update your code as shown below.

Foo.save({ foo: { bar: $scope.baz.bar || "" }})

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

How to capture mouse events using a personalized directive in Angular

One of my projects involves a custom directive named side-menu, which I include in my index.html like this: <side-menu></side-menu> This directive contains a controller that is located in a separate file (SidebarController.js). The template f ...

When it comes to creating APIs in NodeJS for a web application, where is it more effective to verify JSON parameters - on the client side or within the API itself

When developing APIs, do you believe in leaving parameter validation solely to the front end or do you also implement validation within the API itself? Personally, I have been including validation in my APIs, but I am starting to find them becoming overly ...

What is the method for managing binary data within JSON?

I am trying to figure out how to include binary data in a JSON string. I cannot encode the binary data into a base64 string or any other format like that. Essentially, I need to learn how to insert a raw byte array directly into a JSON string. ...

Legend click functionality works well in hiding the bars, but unfortunately, the data values in the charts.js are not being concealed as expected

When I click on the legend, the bar is hidden in the charts.js bar chart. However, the data value associated with the bar is not hidden. I have provided a link to the JS Fiddle code below: Check out the JS Fiddle here: https://jsfiddle.net/npyvw1L8/ var ...

Keep the final item in an array that shares the same attribute

I am working with an array const obj=[{fullCart: 5, halfCart: 4, smu: 3, stowage: 5, index: "FC-093"}, {fullCart: 5, halfCart: 4, smu: 8, stowage: 5, index: "FC-093"}, {fullCart: 5, halfCart: 4, smu: 0, stowage: 5, index: "FC-093 ...

Ways to conceal numerous objects

I need to create a function where I can hide multiple elements by pressing a button based on the value of checkboxes. If a checkbox is checked, the corresponding element should be hidden. Currently, I have some code that only works for the first element: ...

How to implement debouncing for an asynchronous custom validator in Vue.js using vuelidate?

I encountered an issue with my validator function that checks if a username is already registered in the database. The problem was that the request was being sent to the server after every single character input, which was far too frequent. To remedy this, ...

Can you please provide a step-by-step guide for using socket.io with TypeScript and webpack, after installing it

Currently, I am experimenting with TypeScript in conjunction with node.js, socket.io, and webpack. To facilitate this setup, I have configured the webpack.config.js, tsconfig.json, and tsd.json files. Additionally, I acquired the typings file for socket.i ...

Unable to retrieve $wpdb, returning as null

In my development process, I am working on a basic plugin using the Wordpress Plugin Boilerplate. I have implemented AJAX to create an action triggered by a button press to remove an item from a custom database table I have set up. The AJAX function, butto ...

Collect all the attribute values of the checkboxes that have been checked and convert them

Is there a way to retrieve the attribute values of all checked checkboxes as an XML string? <input type="checkbox" id="chkDocId1" myattribute="myval1"/> <input type="checkbox" id="chkDocId2" myattribute="myval43"/> <input type="checkbox ...

Saving a JSONObject to a file

Utilizing the Play framework, I am dealing with a JSONObject that has a specific structure as displayed below (printed in the console) { "rows_map":{ "220":["mahesh", "outfit:bmtech,app:salesreport,uuname,ffname,llname", ...

The search feature in my React Pagination is not performing as effectively as expected

I recently set up a React app that interacts with a MongoDB database using an Express Server. The pagination feature is working smoothly, but I encountered an issue with the search function. It only works when typing in the input box; deleting characters d ...

Finding a specific section on a webpage using AngularJS

Is it possible to create in-page navigation to a specific section within an Angular application without triggering the routing service? For example: The section we want to jump to: <a name="tips"> <div>Tips and tricks...</div> < ...

How come the default is operating when the number is specifically set to 1?

let spans = document.querySelector(`#spans`); let hrs = document.querySelector(`#hrs`); let mins = document.querySelector(`#mins`); let secs = document.querySelector(`#secs`); let start = document.querySelector(`#start`); let stop = document.querySelector( ...

Trigger an animation function with JQuery once the first one has finished

I am attempting to create a step-by-step animation of a div in JQuery. Each animation is triggered by a click, followed by a double-click, and so on. My issue arises when the animations overlap. When I double-click the div, both the first and second anima ...

The condition is not being recognized after clicking the third button

When the button is clicked for the first time in the code snippet below, all divs except for the red one should fade out. With each subsequent click, the opacity of the next div with a higher stack order should be set to 1. Everything works fine until the ...

Utilize selenium IDE to retrieve a specific portion of text and save it as a variable

I am trying to figure out how to extract the number 694575 from a text using Selenium Ide and store it in a variable for future use. Here is the text I am working with: <div class="loginBoxTitle">Edit Exhibition Centre - 694575, Exhibition Center1&l ...

Establishing default parameters for angular pipes

Is there a way to establish default settings for an angular pipe without creating a custom one myself? I frequently utilize the currency pipe in this manner {{ price | currency:'EUR':'symbol':'0.2-2':'de' }} I&apo ...

Is it possible to toggle the status of an item in JSON based on a counter value

Here is the JSON data I have: "questions": { "id": 1, "question": "Select one color", "answers": [ {"id": 1, "answer" : "Green", "isSelected" : false}, {"id": 2, "answer": "Red", "isSelected" : false}, ...

AngularJS variable assignment with HTTP GET operation

The angular filter I have set up is functioning perfectly: categorieFilter = angular.module("categorieFilter", []) categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){ $scope.search = ""; $scope.products = []; $ ...