Angular $http.post

Asked

Viewed 9,598 times

1

I am developing an application with Angularjs and nodejs, where I have to send (POST) the data of a user who is registering. My file Node server.js is as follows::

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');

var app = express();
var authenticationController = require('./server/controllers/authentication-controller.js');


app.use(bodyParser.json());
app.use('/app', express.static(__dirname + "/app" ));
app.use('/node_modules',express.static(__dirname + "/node_modules" ))



app.get('/', function(req, res){
    res.sendfile('index.html');
});

//Authentication
app.post('/api/user/signup', authenticationController.signup);

app.listen('3000', function (){
    console.log("Listening for Local Host 3000");
});

And this is the angular code responsible for carrying out the POST:

var myApp = angular.module('votingApp', []);
myApp.controller('signupController', ['$scope', '$http', function($scope, $http){  
$scope.createUser = function(){
    console.log("teste");
    console.log($scope.user);
    $http.post('api/user/signup', $scope.user).success(function(response){

        }).error(function(error){
            console.log(error);
        console.log("debugMe!");
        })
    }
}]);

The 'signupController' controller is running correctly: 'test' is being printed on the console, and I can also view $Scope.user. But when you run $http.post I get the error in the 'Cannot POST /url' console. 'debugMe' is also printed! ', indicating that it gave error when performing the POST. Because it is not working?

1 answer

2

In good practice, you should never make a request in your controller, always create a service or a Factory for this, following the angular style guide of pope it is recommended you create a Factory and call it in the controller.

Your api is waiting to receive the user?

Try calling it that:

$http({
        url: '/api/user/signup',
        method: "POST",
        data: { 'user' : $scope.user }
    })
    .then(function(response) {
            // success
    }, 
    function(response) { // optional
            // failed
    });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.