Troubleshooting: AngularJS Http Post Method Failing to Execute

I am attempting to make an HTTP POST request to update my database using AngularJS. Although my code is not displaying any errors, the database is not being updated and I'm having trouble pinpointing the issue. Below is the code snippet:

//topic-service.js

  (function() {
        'use strict';
        angular.module('topic').factory('topicService', topicServiceFunction);
        topicServiceFunction.$inject = [ '$http', '$q' ];
        function topicServiceFunction($http, $q) {
            var topicService = {
                getTopics : getTopics

            }
            return topicService;

            function getTopics(obj) {
                console.log('-->topicServiceFunction');
                console.log(obj.name);
                var deferred = $q.defer();
                return $http.post('http://localhost:8080/restapp/api/topic',
                        JSON.stringify(obj)).then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        return deferred.reject(response.data);
                    }
                }, function(response) {
                    return deferred.reject(response.data);
                });

            }

        }

    }())

//topic-controller.js

 (function() {
        'use strict';
        angular.module('topic').controller('topicController',
                topicControllerFunction);
        topicControllerFunction.$inject = [ '$scope', 'topicService' ];
        function topicControllerFunction($scope, topicService) {
            $scope.getTopics = getTopics;
            function getTopics(topicId,name,description,categId,userId) {
                 console.log('-->topictrlFunction');
                $scope.topics = [];

                var obj={
        id:$scope.topicId,
        name:$scope.name,
        description:$scope.description,
        id_category:$scope.categId,
        user_id:$scope.userId

        }
        var promise = topicService.getTopics(obj);
                promise.then(function(data) {
                    if (data != undefined && data != null) {
                        $scope.topics = data;
                    } else {
                        $scope.topics = undefined;
                    }
                }, function(error) {
                    console.log('error=' + error);
                    $scope.topics = undefined;
                })
                topicService.getTopics(obj);
                $scope.topics = topicService.getTopics(obj);
            }

        }
    }())

//topic.html

 <!DOCTYPE html>
    <html lang="en" ng-app="myTopics">
    <head>
    <meta charset="UTF-8">
    <script src="../../../bower_components/angular/angular.js"></script>
    <script src="app.js"></script>
    <script src="topics/module/topic-module.js"></script>
    <script src="topics/controller/topic-controller.js"></script>
    <script src="topics/service/topic-service.js"></script>
    <title>Topics</title>
    </head>
    <body>

        <div ng-controller="topicController">
            <div ng-controller="topicController">
                <p>
                    Topic id: <input type="text" ng-model="topicId">
                </p>
                <p>
                    Name: <input type="text" ng-model="name">
                </p>
                <p>
                    Description: <input type="text" ng-model="description">
                </p>
                <p>
                    Id category: <input type="text" ng-model="categId">
                </p>
                <p>
                    User id: <input type="text" ng-model="userId">
                </p>
                <button ng-click="getTopics(topicId,name,description,categId,userId)">Add
                    topic</button>
                <ul ng-repeat="topic in topics">
                    <li>{{topic.id}} --{{topic.name}} -- {{topic.description}} --
                        {{topic.id_category}}--{{topic.user_id}}</li>
                </ul>

            </div>
    </body>
    </html>

Answer №1

When working on your service, try to avoid using $q and returning $http promise as it can be counterproductive. Instead, consider returning a deferred promise like this:

function getTopics(obj) {

      console.log('-->topicServiceFunction');
      console.log(obj.name);

      var deferred = $q.defer();
      var data = JSON.stringify(obj)

      $http.post('http://localhost:8080/restapp/api/topic', data)
          .then(function(response) {
              if (typeof response.data === 'object') {
                  deferred.resolve(response.data);
              } else {
                  deferred.reject(response.data);
              }
           })
           .catch(function(response) {
              return deferred.reject(response.data);
           });

    return deferred.promise;

 }

If you're still encountering issues, consider sending urlencoded data instead of json:

To do this, simply include the following header in your request:

headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}

Make sure to encode the data using the $httpParamSerializerJQLike service. Don't forget to inject it into your service.

function getTopics(obj) {

      console.log('-->topicServiceFunction');
      console.log(obj.name);

      var deferred = $q.defer();
      var data = $httpParamSerializerJQLike(obj);
      var config = {
         headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
      };

      $http.post('http://localhost:8080/restapp/api/topic', data, config)
          .then(function(response) {
              if (typeof response.data === 'object') {
                  deferred.resolve(response.data);
              } else {
                  deferred.reject(response.data);
              }
           })
           .catch(function(response) {
              return deferred.reject(response.data);
           });

    return deferred.promise;

 }

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 can I efficiently include all css from node_modules in vuejs?

For my Vue.js app built with the webpack template and vuetify, I am starting by importing the vuetify css in my App.vue. <style> @import '../node_modules/vuetify/dist/vuetify.min.css' </style> I'm wondering if this is the c ...

Accessing JSON data in AngularJS from Node.js as the backend and SQL database

I am currently working on a project that involves setting up a node.js server in the backend and using AngularJS in the frontend. In order to fetch information from an SQL database, I have implemented a simple GET request as shown below: req.execute(&apos ...

The JQuery parseFloat() function seems to be consistently returning "NAN" whenever it is used with the .text property

I am currently encountering an issue with parsing the text property of an input element identified by the id currency-converter. My goal is to convert this text into a floating-point value so that I can proceed with applying mathematical operations to conv ...

Unable to successfully link filter outcomes with input in AngularJS

Here is the code snippet I am working with: <body ng-app=""> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {nam ...

What is the mechanism by which a Node.js server handles incoming requests?

Suppose I am working with this code snippet. I am using ExpressJS, although the server part doesn't seem much different from vanilla Node.js. var express=require('express'); var settings=JSON.parse(fs.readFileSync('settings.json' ...

Retrieve a Play Scala variable in the $scope of an AngularJS application

After trying various methods recommended on StackOverflow, I am still struggling to retrieve a Play Scala variable within my Javascript $scope. The line of initialization in an HTML file is as follows: @(playVariable: String)(implicit request: play.api.mv ...

I am experiencing an issue where my Laravel website does not refresh automatically

Having trouble with the URL (url: "/ultimo-pedidox"). It seems to be loading correctly, but the view isn't refreshing as expected. @extends('store/template') @section('content') <div style="margin-top: 55px;" ...

What is the best way to resize an image to fit its surroundings within a nested box?

Have you ever heard of a website called SPAM? It has a unique homepage that I want to replicate using JavaScript, jQuery, and some CSS. My main challenge is figuring out how to adjust the image size to match the center box on the page. I want to create th ...

Retrieve the chosen item to automatically fill in the input fields using Ionic 2 and Angular

My goal is to create a dropdown menu populated with a list of items, and when a product is selected, its price should automatically appear in the quantity field. <ion-item> <ion-label>Item</ion-label> <ion-select (ionChange)="getP ...

The unrevealed node that is requesting the module is leading to an undefined outcome

I'm facing an issue where I need to import var server = require('../../index.js'); in my foo-dao.js file. This is necessary for accessing a hapi server plugin without passing it through the hapi request object from controller to dao. The pr ...

Utilizing Jquery and Ajax to create a dynamic dropdown selection feature based on dependencies from a JSON file

Could you assist with the code snippet below? I have a form where each dropdown list depends on the selection above it. Based on the user's selection, the appropriate data should display in the subsequent dropdown list. I am trying to make dropdown l ...

React does not recognize data.map as a function

Currently, I am facing an issue with a simple map function in React that is supposed to create a set amount of times. {times.map((time) => ( <Pill value={time} handleTimes={handleTimes} key={time} /> ))} The error being thrown i ...

Guide on connecting md-select(s) created within an ng-repeat to various models

Check out this code snippet: <div layout="row" class="row" layout-xs="column" ng-repeat="dataset in datasetsEnv"> <div class="large-12 columns end" flex> <md-input-container layout="row" flex> <label>Environment setting ...

Looking for assistance with overriding kendo UI validation requirements

I'm looking to customize the date validation in my code to validate the date as DD/MM/YYYY. Here's my current code snippet and I'm getting an error message that says: Unable to get property 'methods' of undefined or null referen ...

Is it necessary for me to master React in order to code with React Native?

As I move on to learning React and/or React Native after mastering Angular, it feels like a natural progression in my development journey. My understanding is that React Native could streamline the process of building Android/iOS native apps within one pr ...

Is it possible to employ a jQuery handler as the selector for the .on() method?

Can a jQuery handler $(...) be used as the selector for .on()? The code snippet below illustrates this: how can I change the circle's color to blue without having a plain text representation of my selector, but still using a handler? // This works. ...

Exploring the integration of Stripe Checkout with React and Express.js

Seeking assistance with integrating Stripe Checkout into my React application. I need to create a route in my nodejs/express server that will provide the session id required for setting up Stripe Checkout on the front end. The aim is to redirect users to s ...

inside the connect module, the res._renderHeaders function is located

Currently, I am delving into the patch.js file within the connect module. In it, I found some intriguing code snippets: var http = require('http') , res = http.ServerResponse.prototype , setHeader = res.setHeader , _renderHeaders = res._re ...

Sorting by price using the ng-repeat directive is not suitable for this

Utilizing angular's ng-repeat along with orderBy on a product catalog page to sort the products based on a select change. The ordering by name using orderBy works as expected, however, when it comes to price it sorts like this: 1,10,11,12,13,14,2,3,4 ...

The useTransition() method in React remains stuck in the isPending state when making API calls from routes in the /pages/api directory

I'm encountering an issue with the useTransition() function where it remains true and never changes back to false. I am attempting to delete a record from MongoDB and after completion, I want to refresh the React Server Component following the guideli ...