0

I've wrote this service using node, it works but i don't know how to call it from an angularjs controller, i nedd to call the post method

this is the service:

    var app   = require('express')();
var http = require('http').Server(app);
var mysql = require('mysql');
var bodyParser = require("body-parser");
var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'repositorio',
    });
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/',function(req,res){
    var data = {
        "error":1,
        "Usuarios":""
    };

    connection.query("SELECT * from usuario",function(err, rows, fields){
        if(rows.length != 0){
            data["error"] = 0;
            data["Usuarios"] = rows;
            res.json(data);
        }else{
            data["Usuarios"] = 'Usuarios no encontrados..';
            res.json(data);
        }
    });
    /*var data = {
        "Data":""
    };
    data["Data"] = "Welcome to Book Store DEMO...";
    res.json(data);*/
});

app.post('/usuario',function(req,res){
    var Email = req.query.correo;
    var Password = req.query.contrasena;
    var Nombres = req.query.nombres;
    var Apellidos = req.query.apellidos;
    var Usuario = req.query.usuario;
    var data = {
        "error":1,
        "Usuario":""
    };
    console.log("Email: "+Email+" Password "+Password+" Nombres "+Nombres+" Apellidos "+Apellidos+" Usuario"+Usuario);
    if(!!Email && !!Password && !!Nombres && !!Apellidos && !!Usuario){
        var user ={usu_correo: Email,usu_contrasena: Password,usu_nombres:Nombres,usu_apellidos: Apellidos,usu_usuario:Usuario}
        connection.query('INSERT INTO usuario SET ?',user,function(err, rows, fields){
            if(!!err){
                data["Usuario"] = "Error Adding data";
            }else{
                data["error"] = 0;
                data["Usuario"] = "Usuario adicionado con éxito";
            }
            res.json(data);
        });
    }else{
        data["Usuario"] = "Please provide all required data";
        res.json(data);
    }
});
http.listen(8080,function(){
    console.log("Connected & Listen to port 8080");
});

and this is me trying to connect it with angular, i need help please

var app = angular.module('el_acorde_web', []);

app.controller('usuarioscontroller', function($scope, $http)
{
    $scope.usuario = {};
    $scope.usuario.correo = "[email protected]";
    $scope.usuario.nombres = "David Fernano";
    $scope.usuario.apellidos = "Sotelo";
    $scope.usuario.contrasena = "lakjsdlfkja";
    $scope.usuario.usuario = "davidstl5";


    $scope.registrar = function(){
        $http.post('http://localhost:8080/usuario', $scope.usuario)
        .success(function(data) 
        {
            alert(data);
        })
        .error(function(data) 
        {
            alert('Error:' + data);
        });
    }
});
4
  • If you change success to then, does it work? Commented May 9, 2016 at 5:13
  • maybe dup of stackoverflow.com/questions/32515171/… Commented May 9, 2016 at 5:17
  • are u getting response? Commented May 9, 2016 at 5:34
  • No. I've no Idea why i can't connect them Commented May 9, 2016 at 5:54

2 Answers 2

0

Your code looks fine, can I see the HTML code where you are calling the registrar function? Looks like you only have to add the ng-click directive if everything else is working, and for a best practice I would create a factory or a service and call a function there that interacts with the Node app.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm not down voting as you are new, but this should be a comment not an answer.
<button type='button' ng-disabled='btnRegistrar == false' ng-click='registrar()'>Registrar</button>
Ok, thanks for the tip @mJunaidSalaat, didn't see the comment textfield yesterday
0

I found the solution! Chrome is the problem we install https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

and then use:

$scope.registrar = function(){
        alert("Entre");
        /*$http.post('http://localhost:8080/usuario', $scope.usuario)
        .success(function(data) 
        {
            alert(data);
        })
        .error(function(data) 
        {
            alert('Error:' + data);
        });*/

        var datos = {correo: $scope.usuario.correo, contrasena: $scope.usuario.contrasena,
                                nombres:$scope.usuario.nombres, apellidos:  $scope.usuario.apellidos,
                              usuario: $scope.usuario.usuario};

        var request = $http({
            method: "POST",
            url: "http://localhost:8080/usuario",                    
            data: datos,
            headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Basic ' + btoa(datos), 
            'Access-Control-Allow-Origin': "*"}
        });

        request.success(
            function( data ) {
                alert(data);
            }
        );

        request.error(
            function( data ) {
                alert(data);
            }
            );
    }

and everything works!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.