简体   繁体   English

AngularJS不向NodeJS服务器发送数据

[英]AngularJS don't send data to NodeJS server

Im new with NodeJS and Im trying to send data to server with Angular 我是NodeJS的新手,我试图用Angular将数据发送到服务器

$scope.logearse = function () {
        $http({
            method: "POST",
            url: "http://localhost:8888/login",
            data: $scope.usuario
        }).then(function successCallback(response){
                console.log(response)
        }, function errorCallback(error){
            alert("No se han podido enviar los datos")
        })
    } 

But in the server when I try to receipt the request is always {} 但是在我尝试接收请求的服务器中总是{}

http.createServer(function(peticion, respuesta){

    console.log(peticion.url)
    console.log(peticion)
    // We begin with "login"

    if (peticion.url == "/login") {
        console.log("Inside of Login)

        var datosUsuarioLogin = '';

        peticion.addListener("data", function(chunk) {
            datosUsuarioLogin += chunk;

        // function called when a new chunk of data is recibed
        });

        peticion.addListener("end", function() {
            // When the data is recibed is transformed in JSON
            var datosUsuarioLoginObjeto = querystring.parse(datosUsuarioLogin);
            recuperarDatos(datosUsuarioLoginObjeto, respuesta);
            console.log(datosUsuarioLoginObjeto) //return {}
        });
        //End of LOGIN "if"
    }
    }).listen(8888)

The thing is the same code works if I use a form with a regular submit but no if I try to use the $http of ANGULAR. 如果我使用带有常规提交的表单,但是如果我尝试使用ANGULAR的$ http,则该代码可以使用相同的代码。

I try to use "params" instead of "data" but "params" transform the data in the URL and the code dont works. 我尝试使用“params”而不是“data”,但“params”转换URL中的数据并且代码不起作用。

You need to use bodyParser to parse the request body and place the result in request.body of route. 您需要使用bodyParser来解析请求主体并将结果放在request.body of route中。

app.use(express.bodyParser());

And the request: 请求:

$http({
      method: "POST",
      url: "http://localhost:8888/login",
      contentType: "application/json",
      data: $scope.usuario // if usuario is not a valid json, you could to use JSON.stringify($scope.usuario);

Ok, after a lot of time trying finnaly I use Express but the version of Express I use dont allow simply bodyParser I need to install the body parser middleware Link to body-parser 好吧,经过大量的时间尝试finnaly我使用Express但我使用的版本不允许简单的bodyParser我需要安装身体解析器中间件链接到body-parser

And the code 和代码

var bodyParser = require('body-parser'); 
var jsonParser = bodyParser.json();

app.post('/', jsonParser, function (request, response) {
response.send(request.body) 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM