简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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