如何从angularjs $ http.post中读取/保存nodeJs中的json文件

厌恶糟糕的英语

我有一个问题,试图抓住一个json使用$ http.post fron一个angularjs发送到一个nodejs express(我必须发送它,因为我不能在客户端保存在服务器上的文件)

我有这个代码在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 } } } 

如果你想在Node中生成一个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'); } }); 

你正在访问variables错误。

在POST数据上,尝试GET数据的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);