Unexpected behavior encountered when using the $http.post method

I've been working with a component that I utilized to submit data to the Rest API. The code snippet for the component is as follows:

(function(angular) {
    'use strict';
    angular.module('ComponentRelease', ['ServiceRelease'])
        .component('createRelease', {
            templateUrl: 'components/release/createRelease.html',
            controller: CreateRelease,
            controllerAs: 'clCtrl',
        })

    function CreateRelease($http, getReleaseManagers, insertRelease) {
        var ctrl = this;

        this.$onInit = function() {
            getReleaseManagers.promise($http).then(function(response) {
                ctrl.managers = response.data.releasemanager;
            });

            //the save button
            ctrl.save = function() {
                var release = { "rName": ctrl.r_name, "releaseDate": ctrl.r_date, "releaseSharepoint": ctrl.r_sharepoint, "gManager": ctrl.gname, "pManager": ctrl.pname };

                $http.post('http://localhost:8080/post', release).then(function(response) {
                    console.log("Save in database");
                }, function(e) {
                    console.log(e);

                });
            };
        };
    };
})(window.angular);

When I check the console log after saving, I see "undefined" if it was successful and an error message if there were any errors. Is my understanding correct? If the post was successful, shouldn't I see the message "Save in Database"? I would appreciate your insights on this matter. I am currently using angularjs 1.6

Thank you for your assistance, Eugen

Answer №1

When posting in Angular, make sure to include the header content-type in the configuration so that the server can properly parse the data type (application/json).

(function(angular) {
  'use strict';
  angular.module('ComponentRelease', ['ServiceRelease'])
    .component('createRelease', {
      templateUrl: 'components/release/createRelease.html',
      controller: CreateRelease,
      controllerAs: 'clCtrl',
    })

  function CreateRelease($http, getReleaseManagers, insertRelease) {
    var ctrl = this;

    this.$onInit = function() {
      getReleaseManagers.promise($http).then(function(response) {
        ctrl.managers = response.data.releasemanager;
      });

      //the save button
      ctrl.save = function() {
        var release = {
          "rName": ctrl.r_name,
          "releaseDate": ctrl.r_date,
          "releaseSharepoint": ctrl.r_sharepoint,
          "gManager": ctrl.gname,
          "pManager": ctrl.pname
        };

        var config = {
          headers: {
            'Content-Type': 'application/json'
          }
        }

        $http.post('http://localhost:8080/post', release, config).then(function(response) {
          console.log("Save in database");
        }, function(e) {
          console.log(e);

        });
      };
    };
  };
})(window.angular);

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

What sets declaring variables apart in Vue?

Can you clarify the distinctions among various methods of declaring variables? When should I employ each of these declaration methods? <script> const someVariable = 12345 export default { name: 'App', } </script> <script> e ...

What distinguishes setting a $watch on a string variable from setting a $watch on an object's key in AngularJS?

When using angularJs, I am curious about the distinction between setting $watch on a string variable versus setting $watch on an Object's key. Let me explain with a detailed scenario: $scope.activeMenu = {'id' : '...', 'name ...

What is the best way to use JavaScript to click on a block and retrieve its attribute value?

Struggling to capture the data-id attribute value of each item on click, despite researching online. Seeking guidance as I navigate the learning process and encounter programming frustrations. document.addEventListener("click", handle); const demo = e. ...

Angular 2: Issue with Component not reinitializing when query parameters change

I am currently working with Angular 2 and the latest router component to create a search functionality. Upon clicking the search button for the first time, the router navigates to the search component and retrieves data from the service. However, I have no ...

Selecting a value will cause other blocks to vanish

How do I hide other filter buttons when I select a value? Check out my code snippet below: const FilterBlock = props => { const { filterApi, filterState, filterFrontendInput, group, items, name, ...

A guide on using Javascript to write information to a JSON file

Let's consider an example where we have a .JSON file with the following content: [{"honda": "accord", "color": "red"},{"ford": "focus", "color": "black"}] We are looking to add another object {"nissan": "sentra", "color": "green"} into this existing ...

Navigating with AngularJS through link redirection using anchor tags

How can I achieve smooth scrolling to a specific section using angularJS when clicking on a link? When clicking on a link like this: The page instantly redirects to the specified footer section. I want to implement an angular controller to handle this fun ...

What is the interaction between Vue's v-model and the update:modelValue directive, and how can we customize the default behavior to prevent it from

Could someone provide an explanation of the usage of v-model with :modelValue and update:modelValue? What happens when both are used together? In the code snippet below, a component is shown: <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3. ...

Forget the function once it has been clicked

I'm looking for a solution to my resizing function issue. When I press a button, the function opens two columns outside of the window, but I want to reset this function when I click on another div. Is there a way to remove or clear the function from m ...

Having difficulty parsing or assigning JSON response: The response is being interpreted as [object Object]

Working with the Flickr API, Javascript/JQuery, and AJAX, I have the following code: function getRequest(arguments) { var requestinfo; $.ajax({ type: 'GET', url: flickrurl + '&'+ ...

Please send the element that is specifically activated by the onClick function

This is the HTML code I am working with: <li class="custom-bottom-list"> <a onClick="upvote(this)"><i class="fa fa-thumbs-o-up"></i><span>upvote</span></a> </li> Here is my JavaScript function for Upvot ...

Strategies for handling missing and unused keys in i18n language files

In the realm of Rails/Angular webapps, we have a unique way of translating our app. We utilize both Ruby Globalize i18n with yml language files and angular-translate with json language files. However, managing these language files can become quite arduous. ...

What could be causing axios to not function properly when used with async/await in this particular scenario

I need to update the DoorState when a button is clicked. After sending a request to the API to change the DoorState, I then call another API to check the status of the robot. Even though the DoorState has been successfully changed, it seems that the chan ...

Displaying a notification for a multi-selection using JavaScript

I need help with a piece of Html code I have. It's a list of countries, and what I want is to show an alert when one or more countries are selected to display which ones were chosen. I'm working with JavaScript only and don't want to use Jqu ...

Tips for incorporating dynamic URLs in Next.js

In my current project using nextjs, I am dealing with fetching images via an API. Right now, I am receiving the "Full image path" (for example, "https://myurl.com/image/imagename.jpg") without any issue. However, I need to figure out how to fetch the image ...

Refresh a particular element using javascript

I'm new to Javascript and I am trying to refresh a specific element (a div) using only Javascript when that div is clicked. I came across the location.reload() function, but it reloads the entire page which doesn't fit my requirements. Upon clic ...

Transform jQuery code to its equivalent in vanilla JavaScript

While I am proficient in using jQuery, my knowledge of pure JavaScript is somewhat limited. Below is the jQuery code that I have been working with: $(document).ready(function() { $.get('http://jsonip.com/', function(r){ var ip_addre ...

Resizing an image with six corners using the canvas technique

Currently, I am facing two issues: The topcenter, bottomcenter, left and right anchors are not clickable. I'm struggling with the logic to adjust the image size proportionally as described below: The corner anchors should resize both height and wi ...

Cross-Origin Resource Sharing (CORS) issue: The Access-Control-Allow-Headers in preflight response does not allow the Authorization request header field

I am currently attempting to send a request from one localhost port to another. Specifically, I am utilizing angularjs on the frontend and node on the backend. Given that this is a CORS request, in my node.js code, I have implemented the following: res.h ...

Executing javascript href using Python in Selenium

Currently, I am attempting to use Selenium in Python to click on a href JavaScript link. The HTML code appears as follows: HTML Example and my goal is to click on javascript:goType(1). This is the approach I have taken: advance_search = browser.find_el ...