Angular $ http.post

1

I'm developing an application with angularJS and nodeJS, where I have to send (POST) the data of a user that 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 performing 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 driver 'signupController' is running correctly: 'test' is being printed on the console, and I can also correctly view the $ scope.user. But when I run the $ http.post I get the error in the console 'Can not POST / url'. It also prints 'debugMe!', Indicating that it made an error at the time of POST. Why is not it working?

    
asked by anonymous 21.12.2016 / 06:01

1 answer

1

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

Is your api waiting to receive the user?

Try to call it like this:

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