TeddyG
TeddyG

Reputation: 559

unable to post to node.js - express from angularjs

I am trying to post some data to node.js - express server from my angularjs front end and I do not think that my post request is ever getting to my server.

Here is some basic angularjs on the front-end:

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);
    });   
}]);

Here is a basic back-end:

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);

However the server is not logging any of the data send from the front-end. I am not sure if the POST request is even getting to the server since it is not logging any of the data to the console. Any help/suggestions would be appreciated.

Upvotes: 0

Views: 542

Answers (1)

user2226755
user2226755

Reputation: 13223

Check your header.

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
});

Maybe add $http.write(data);

Upvotes: 1

Related Questions