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 = "davidstl5@gmail.com";
    $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);
        });
    }
});

2 Answers2

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.

Yasu Flores
  • 121
  • 3
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!