Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

SORRY FOR BAD ENGLISH

I have a problem trying to catch a json sended using $http.post fron an angularjs to a nodejs with express (i have to send it because i can not save in client side a file on the server)

i have this code in angularjs

var app = angular.module('angularTable', []);
app.controller('listdata',function($scope, $http){
    $scope.users = []; //declare an empty array
    $http.get("data/people.json").success(function(response){ 
        $scope.users = response; //this works well
    });
    $scope.add = function(){
    $scope.users.push({'id':$scope.users.length,'name':$scope.name,'age': $scope.age}); //this works well
    $http.post("data",$scope.users).success(function(data, status, headers, config){ //this send to the nodeJs the object
            console.log("success");
        }).error(function(data,status,headers,config){
            console.log("error");
        });
}
});

and this in server nodeJs

var express = require('express');
var app = express();
app.use('/data', express.static(__dirname + '/data/')); //this is for routing
app.post("/data", function(req,res){
    console.log(req); //this return me something (that i do not understand)***********
    console.log(req.name); //this return me undefined
THIS IS WHERE I NEED THE JSON THAT I SEND FROM ANGULARJS TO SAVE INTO A EXISTENT JSON FILE IN THE SERVER (/data/people.json)
});
app.listen(5050);´

this is the json file

[{
    "id": 0,
    "age": 24,
    "name": "Mathis Hurst"
}, {
    "id": 1,
    "age": 38,
    "name": "Gallegos Ryan"
}, {
    "id": 2,
    "age": 27,
    "name": "Jodi Valencia"
}, {
    "id": 3,
    "age": 28,
    "name": "Jenna Anderson"
}, {
    "id": 4,
    "age": 28,
    "name": "Horne Clark"
}, {
    "id": 5,
    "age": 21,
    "name": "Briggs Walters"
}, {
    "id": 6,
    "age": 27,
    "name": "Rena Higgins"
}, {
    "id": 7,
    "age": 32,
    "name": "Adrian Marquez"
}, {
    "id": 8,
    "age": 25,
    "name": "Alberta Ellison"
}, {
    "id": 9,
    "age": 20,
    "name": "Mcleod Stark"
}, {
    "id": 10,
    "age": 22,
    "name": "Neal Patrick"
}, {
    "id": 11,
    "age": 36,
    "name": "Williamson Roman"
}

]

this is what console.log(req); returns:

        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     allowHalfOpen: true,
     destroyed: false,
     bytesRead: 0,
     _bytesDispatched: 970,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: 
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        _connections: 3,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::5050' },
     _server: 
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        _connections: 3,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::5050' },
     _idleTimeout: 120000,
     _idleNext: 
      Socket {
        _connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: null,
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 10,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        destroyed: false,
        bytesRead: 0,
        _bytesDispatched: 244,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Circular],
        _idleStart: 2771,
        parser: [Object],
        on: [Function: socketOnWrap],
        _paused: false,
        read: [Function],
        _consuming: true,
        _httpMessage: null },
     _idlePrev: { _idleNext: [Circular], _idlePrev: [Object] },
     _idleStart: 3075,
     parser: 
      HTTPParser {
        '0': [Function: parserOnHeaders],
        '1': [Function: parserOnHeadersComplete],
        '2': [Function: parserOnBody],
        '3': [Function: parserOnMessageComplete],
        '4': [Function: onParserExecute],
        _headers: [],
        _url: '',
        _consumed: true,
        socket: [Circular],
        incoming: [Circular],
        outgoing: null,
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncoming] },
     on: [Function: socketOnWrap],
     _paused: false,
     read: [Function],
     _consuming: true,
     _httpMessage: 
      ServerResponse {
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: false,
        chunkedEncoding: false,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: true,
        sendDate: true,
        _removedHeader: {},
        _contentLength: null,
        _hasBody: true,
        _trailer: '',
        finished: false,
        _headerSent: false,
        socket: [Circular],
        connection: [Circular],
        _header: null,
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: [Function: updateOutgoingData],
        req: [Circular],
        locals: {} } },
  httpVersionMajor: 1,
  httpVersionMinor: 1,
  httpVersion: '1.1',
  complete: false,
  headers: 
   { host: 'localhost:5050',
     connection: 'keep-alive',
     'content-length': '544',
     accept: 'application/json, text/plain, */*',
     origin: 'http://localhost:5050',
     'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36',
     'content-type': 'application/json;charset=UTF-8',
     dnt: '1',
     referer: 'http://localhost:5050/',
     'accept-encoding': 'gzip, deflate',
     'accept-language': 'es-419,es;q=0.8,en-US;q=0.6,en;q=0.4',
     cookie: '___r56138=0.9179862105555572' },
  rawHeaders: 
   [ 'Host',
     'localhost:5050',
     'Connection',
     'keep-alive',
     'Content-Length',
     '544',
     'Accept',
     'application/json, text/plain, */*',
     'Origin',
     'http://localhost:5050',
     'User-Agent',
     'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36',
     'Content-Type',
     'application/json;charset=UTF-8',
     'DNT',
     '1',
     'Referer',
     'http://localhost:5050/',
     'Accept-Encoding',
     'gzip, deflate',
     'Accept-Language',
     'es-419,es;q=0.8,en-US;q=0.6,en;q=0.4',
     'Cookie',
     '___r56138=0.9179862105555572' ],
  trailers: {},
  rawTrailers: [],
  upgrade: false,
  url: '/data',
  method: 'POST',
  statusCode: null,
  statusMessage: null,
  client: 
   Socket {
     _connecting: false,
     _hadError: false,
     _handle: 
      TCP {
        _externalStream: {},
        fd: 15,
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        onconnection: null,
        writeQueueSize: 0 },
     _parent: null,
     _host: null,
     _readableState: 
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _events: 
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        drain: [Object],
        timeout: [Function],
        error: [Function: socketOnError],
        close: [Object],
        data: [Function: socketOnData],
        resume: [Function: onSocketResume],
        pause: [Function: onSocketPause] },
     _eventsCount: 10,
     _maxListeners: undefined,
     _writableState: 
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     allowHalfOpen: true,
     destroyed: false,
     bytesRead: 0,
     _bytesDispatched: 970,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: 
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        _connections: 3,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::5050' },
     _server: 
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        _connections: 3,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::5050' },
     _idleTimeout: 120000,
     _idleNext: 
      Socket {
        _connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: null,
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 10,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        destroyed: false,
        bytesRead: 0,
        _bytesDispatched: 244,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Circular],
        _idleStart: 2771,
        parser: [Object],
        on: [Function: socketOnWrap],
        _paused: false,
        read: [Function],
        _consuming: true,
        _httpMessage: null },
     _idlePrev: { _idleNext: [Circular], _idlePrev: [Object] },
     _idleStart: 3075,
     parser: 
      HTTPParser {
        '0': [Function: parserOnHeaders],
        '1': [Function: parserOnHeadersComplete],
        '2': [Function: parserOnBody],
        '3': [Function: parserOnMessageComplete],
        '4': [Function: onParserExecute],
        _headers: [],
        _url: '',
        _consumed: true,
        socket: [Circular],
        incoming: [Circular],
        outgoing: null,
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncoming] },
     on: [Function: socketOnWrap],
     _paused: false,
     read: [Function],
     _consuming: true,
     _httpMessage: 
      ServerResponse {
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: false,
        chunkedEncoding: false,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: true,
        sendDate: true,
        _removedHeader: {},
        _contentLength: null,
        _hasBody: true,
        _trailer: '',
        finished: false,
        _headerSent: false,
        socket: [Circular],
        connection: [Circular],
        _header: null,
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: [Function: updateOutgoingData],
        req: [Circular],
        locals: {} } },
  _consuming: false,
  _dumped: false,
  next: [Function: next],
  baseUrl: '',
  originalUrl: '/data',
  _parsedUrl: 
   Url {
     protocol: null,
     slashes: null,
     auth: null,
     host: null,
     port: null,
     hostname: null,
     hash: null,
     search: null,
     query: null,
     pathname: '/data',
     path: '/data',
     href: '/data',
     _raw: '/data' },
  params: {},
  query: {},
  res: 
   ServerResponse {
     domain: null,
     _events: { finish: [Function: resOnFinish] },
     _eventsCount: 1,
     _maxListeners: undefined,
     output: [],
     outputEncodings: [],
     outputCallbacks: [],
     outputSize: 0,
     writable: true,
     _last: false,
     chunkedEncoding: false,
     shouldKeepAlive: true,
     useChunkedEncodingByDefault: true,
     sendDate: true,
     _removedHeader: {},
     _contentLength: null,
     _hasBody: true,
     _trailer: '',
     finished: false,
     _headerSent: false,
     socket: 
      Socket {
        _connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: null,
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 10,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        destroyed: false,
        bytesRead: 0,
        _bytesDispatched: 970,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 3075,
        parser: [Object],
        on: [Function: socketOnWrap],
        _paused: false,
        read: [Function],
        _consuming: true,
        _httpMessage: [Circular] },
     connection: 
      Socket {
        _connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: null,
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 10,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        destroyed: false,
        bytesRead: 0,
        _bytesDispatched: 970,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 3075,
        parser: [Object],
        on: [Function: socketOnWrap],
        _paused: false,
        read: [Function],
        _consuming: true,
        _httpMessage: [Circular] },
     _header: null,
     _headers: { 'x-powered-by': 'Express' },
     _headerNames: { 'x-powered-by': 'X-Powered-By' },
     _onPendingData: [Function: updateOutgoingData],
     req: [Circular],
     locals: {} },
  route: Route { path: '/data', stack: [ [Object] ], methods: { post: true } } }
share|improve this question
    
in code comments you say "//this return me something (that i dondt understand)". What exactly is it returning? It's not possible to help you understand it if we can't see what it is. – Claies Jun 7 at 18:23
    
share the output from console.log(req); in your question – theaccordance Jun 7 at 18:34
    
already update the output. can you see it? – Humberto Gutierrez Jun 7 at 18:49

If you're looking to generate a json file within Node, first include the fs module:

var fs = require('fs');

Next, add this snippet where you need the json file generated:

fs.writeFile('/data/people.json'), JSON.stringify(req.body, null, 4), function (err) {
    if (err) {
        console.log('error writing /data/people.json');
    } else {
        console.log('JSON file written to /data/people.json');
    }
});
share|improve this answer
    
req.body returns me undefined – Humberto Gutierrez Jun 7 at 18:30
    
Sounds like you're not posting the data properly then – theaccordance Jun 7 at 18:31
    
how is the right way to do it? – Humberto Gutierrez Jun 7 at 18:45
    
If you want additional assistance from me, please respond to the comment I left on your question – theaccordance Jun 7 at 18:47

You're accessing variables wrong.

on POST data, try req.body.yourvariable on GET data, try req.query.yourvariable

var express = require('express');
var app = express();
app.use('/data', express.static(__dirname + '/data/')); //this is for routing
app.post("/data", function(req,res){
    console.log(req.body.name); // this should work.
    // your saving routine here.
});
app.listen(5050);
share|improve this answer
    
it gives me undefined, this is how i pass the json $http.post("data",$scope.users).success(function(data, status, headers, config){ //this send to the nodeJs the object console.log("success"); }).error(function(data,status,headers,config){ console.log("error"); }); – Humberto Gutierrez Jun 7 at 18:36
    
try req.body.data – Nika Jun 7 at 18:37
    
also try do this: $http.post("/data",$scope.users) <-- notice slash. – Nika Jun 7 at 18:39
    
this is the error that i get: TypeError: Cannot read property 'data' of undefined – Humberto Gutierrez Jun 7 at 18:44
    
Check your network tabs logs. In that case POST should not be successful. POST data isn't even getting to handler. – Nika Jun 7 at 18:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.