How to send data using the AngularJS HTTP POST method

Having trouble with posting data back to mongodb - when I click submit, it's not sending anything. The command prompt shows {} and the network console hangs on pending before eventually failing due to a long delay in posting.

Could use some help figuring this out, thanks in advance.

HTML:

<input type="text" ng-model="vm.user">
<input type="text" ng-model="vm.pass">

Service:

function _postUser(user, pass){
        var params = {
            user: user,
            pass: pass
        }
        return $http({
            method: 'POST',
            url: '/loginDB',
            params: params
        })
    }

Fetching users from the database:

vm.getUsers = function (){
        homeService.getUsers()
            .then(function(response){
                vm.users = response.data;
                console.log(vm.users);
            });
    }

Posting action:

vm.postUser = function() {
        // console.log('send it back')
        homeService.postUser(vm.user)
            .then(function(response){
                console.log('send it back')
            })
    }

Server.js handling post request to the database:

app.post('/loginDB', function (req, res){
console.log(req.body);
});

Update: Data is now being posted but not capturing the ng-model values. I suspect an issue with the ng-model but can't pinpoint it.

db.loginDB.insert(req.body, function(err, doc){
    res.json(doc);
})

Answer №1

Consider changing the params key to data

 return $http({
        method: 'POST',
        url: '/loginDB',
        data: params
    })

Also, ensure that the model is consistent for both inputs in the HTML,

controller declaration,

vm.newuser = {user:'',pass:''};

html

<input type="text" ng-model="vm.newuser.user">
<input type="text" ng-model="vm.newuser.pass">

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

Dynamically loading components within an Angular application

I am tasked with displaying different components at specific times by iterating through them. Below is an example of how I have attempted to achieve this. The components I can use are determined by the server. <ngb-tabset [activeId]="1"> ...

Having difficulty with the useState hook in a material ui functional component that integrates with Firebase

Currently, I am endeavoring to create a sign-up form utilizing a Material UI functional component. Within this form, I am aiming to trigger a signup event by using the "onClick" attribute attached to the sign-up button. My approach involves passing the ema ...

Exploring JSON data in a systematic manner

Currently, I am working with a JSON string and encountering a problem. When I run console.log(record.seenTime.time.seenEpoch), I am able to see the correct information. However, if I try console.log(record.seenTime.time[0].seenEpoch), I receive an error m ...

The synergy of Sails, Angular, and Jasmine combined creates a

Utilizing SailsJS for the backend and Angular for the frontend has been a successful combination thus far. I have already implemented Mocha tests for the backend logic in SailsJS and now I am looking to add some tests for the frontend Angular code. Howeve ...

Using JavaScript and jQuery to make calls to the Web API

I am struggling with Java-script callback due to lack of experience. Can anyone provide assistance in resolving the issues I am facing with the code? My goal is to perform a callback from a .json file and search it by ID. While I can display all customers, ...

One interesting aspect of angular .service() is how its singletons allow for the sharing of data across controllers, despite each instance being instantiated as new

Check out the following vanilla JavaScript code snippet: var newable = function() { this.name = 'First'; this.setName = function(name) { this.name = name; } this.getName = function() { return this.name; } } var n = new newab ...

What is the best way to inform my controller about the loading data progress?

In the midst of developing a complex AngularJS application, my main focus is on bundling all Ajax code within separate services that can be accessed by controllers for data retrieval. However, there arises an issue concerning the necessity to track the sta ...

Why won't hover over function properly in separate divs for two items?

My goal is to show text when hovering over a logo, but the text and logo are in different divs. Despite trying various solutions like using display: none and display: block, I still can't get it to work. import styles from '../styles/Float.module ...

Using C# to showcase images stored in a directory on an asp.net platform with an elegant prettyphoto slider

I am currently utilizing the prettyphoto slider to showcase a collection of images stored in a folder on my ASP.NET website. Below is the code I have written to retrieve the images: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBac ...

Creating a personalized news feed using getstream.io in Node.js - a step-by-step guide

const stream = require('getstream'); // Setting up a newsfeed stream using getstream const client = stream.connect( null, ); // Defining a feed for user1 var user1 = client.feed('user', 'user1'); // Adding a custom activity ...

Retrieve access from a different directive

Snippet: (function(){ angular.module('app', []) .controller('controller', function($scope){ $scope.data = "Hello"; }) .directive('myButton', function(){ return { restrict : ...

execute a task automatically for a designated duration of time

I have a specific task that needs to be executed for a defined period of time. Currently, I am utilizing the set interval function, but I require a dynamic timeout period fetched from a database. In the getInactiveTimePeriod function, I retrieve the time f ...

Exploring Angular JS: Understanding the Framework's Structure and FAQs

After diving into the world of AngularJS and familiarizing myself with its tutorial and documentation, I find myself in need of guidance on organizing the structure of my project. My goal is to create a single page app with different main sections such as ...

Delays can occur in CSS when transitioning an element's visibility from `visible` to `hidden`

I have a navigation bar with three elements arranged horizontally from left to right: socialMediaIcons, logoArea, and navBarOptionsList. I've written JavaScript and CSS code that changes the visibility of socialMediaIcons and navBarOptionsList to hid ...

What is the method to determine the overall size of a webpage using the Google PageSpeed API?

"analytics": { "cssResponseBytes": "333 kB", "htmlResponseBytes": "269 kB", "imageResponseBytes": "3.35 MB", "javascriptResponseBytes": "2.29 MB", "numberCssResources": 2, "numberHosts": 80, "numberJsResources": 72, "numberR ...

Retrieve data from MongoDB by querying for a specific field with spaces removed using Mongoose

Is it possible to create a mongoose query that retrieves data from a specific field without spaces? For example, 'KA 04 A' and 'KA04A' should be considered the same. I need to check if a new series already exists in my MongoDB using Mo ...

Transform an asynchronous callback into an asynchronous generator format

I have the following function from a third-party package that I am unable to modify async function runTransaction(callback) { const client = await createClient(); try { await client.query("BEGIN"); await callback(client); } ...

Transform array of objects into a two-dimensional array

Is there a way to transform the following group of objects into a 2D array? var tags= [ {id: 0, name: "tag1", project: "p1", bu: "test"}, {id: 1, name: "tag2", project: "p1", bu: "test"}, {i ...

Parsing an entire JSON array using Moment JS and formatting numerous instances of dates

I am working with an array of JSON objects retrieved from my MVC controller. These objects contain date fields that I need to parse and format. By using the Newtonsoft.Json library in place of the default MVC JSON serialiser, my dates are already formatte ...

The v-for directive is displaying my list in a single row with multiple columns instead of in a single column with multiple rows

Can someone please assist in rendering my list as shown below: A B C The current rendering looks like this: 1: A 2: B 3: C Below is the code snippet: To-Do List: <input type="text" class = "todo" placeholder = "Next Item" v-on:keyup.enter="add ...