无法发布到node.js - 从angularjs表达

时间:2014-07-01 13:00:19

标签: javascript node.js angularjs express

我正在尝试将一些数据发布到node.js - 从我的angularjs前端表达服务器,我认为我的帖子请求不会到达我的服务器。

以下是前端的一些基本角色:

myApp.controller('myController', ['$scope', '$http', function($scope, $http){

    $scope.items = null;

    $http({method: 'POST', 
        url: 'http://localhost:5000/post', 
        data: 'some data'
    }).success(function(data){
        $scope.items = data;
        console.log(data);
    }).error(function(data, statusText){
        console.log(statusText + ': ' + data);
    });   
}]);

这是一个基本的后端:

var express = require('express');
var app = express();

app.post('/post', function(req, res){    
    console.log(req.url);
    console.log(req.method);
    console.log(req.body);

    res.end('some response data');

});

app.listen(5000);

但是,服务器未记录从前端发送的任何数据。我不确定POST请求是否甚至到达服务器,因为它没有将任何数据记录到控制台。任何帮助/建议将不胜感激。

1 个答案:

答案 0 :(得分:1)

检查标题。

data = 'some data';
$http({
    host: "localhost:5000",
    port: "80",
    path: "post",
    method: "POST",
    headers: {
        //"User-Agent": "NodeJS/1.0",
        "Content-Type": "application/x-www-form-urlencoded",
        "Content-Length": data.length
    },
    data: data
});

可能会添加$http.write(data);