2016-06-07 41 views
1

SORRY保存在一個的NodeJS JSON文件的英文不好

我有一個問題想抓住sended使用JSON $ http.post弗朗的angularjs與一個明確的NodeJS (我要送,因爲我不能在客戶端在服務器上保存的文件)

我有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"); 
     }); 
} 
}); 

此代碼,這在服務器的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);´ 

這是JSON文件

[{ 
    "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" 
} 

]

這是執行console.log(REQ);返回:

 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 } } } 
+0

評論你說 「//這回我的東西(我dondt明白)」 。什麼*確切*它是否返回?如果我們看不到它是什麼,就不可能幫助你理解它。 – Claies

+0

共享'console.log(req);'在你的問題 – theaccordance

+0

已經更新輸出。你能看見它嗎? –

回答

1

如果你正在尋找產生內節點一個JSON文件,首先包括fs模塊:

var fs = require('fs'); 

接下來,添加這段代碼,你需要生成的JSON文件:

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'); 
    } 
}); 
+0

req.body返回我undefined –

+0

聽起來像你沒有正確發佈數據然後 – theaccordance

+0

如何正確地做到這一點? –

0

您正在訪問變量錯誤。

的POST數據,嘗試req.body.yourvariable 上獲取數據,嘗試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); 
代碼
+0

它給我undefined, 這是我如何通過json '$ http.post(「data」,$ scope.users)。成功(函數(數據,狀態,頭文件,配置){//發送給節點的對象) console.log(「success」); })。error(function(data,status,headers,config){ console.log(「error」); });' –

+0

嘗試req.body.data – Nika

+0

也嘗試這樣做:$ http.post(「/ data」,$ scope.users)< - 通知斜槓。 – Nika