来自post请求的有效负载在node.js函数中不可用

我刚刚开始摆弄三个(对我而言)新的框架/产品:MongoDB,NodeJS和AngularJS。

我要完成的工作是让一个简单的表单提交一个值,并将该值写入数据库。我已经到了我在Angular应用程序中使用$ http.post提交我的值的时候,我确实调用了我的node.js后端函数,但是我的req参数(下面的se)未定义。在Google Chromes网络监视器中,我看到提交了POST请求,并且有效负载中包含我输入的值。

我真的不明白为什么在接收端不可用。请帮忙。

现在来看一些片段(不是整个文件):

server.js:

var express = require('express'),
menu = require('./routes/menu'),
http = require('http'),
app = express(),
httpServer = http.createServer(app),
bodyParser = require('body-parser');

app.use(bodyParser.json());

app.set('port', 3000);

app.use(express.static(__dirname));

app.get('/menuItems', menu.getMenuItems);
app.post('/menuItems', function(req, res) { console.log(req); });

httpServer.listen(app.get('port'), function () {
    console.log("Express server listening on port %s.", httpServer.address().port);
});

menu.js:

exports.addMenuItem = function(req, res) {
var menuItem = req.body;  <===req.body is undefined
console.log('Adding menuItem: ' + JSON.stringify(menuItem)); 

db.collection('menuItems', function(err, collection) {
    collection.insert(menuItem, {safe:true}, function(err, result) {
        if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            console.log('Success: ' + JSON.stringify(result[0]));
            res.send(result[0]);
        }
    });
});

};

app.js:

(function () {
var app = angular.module('jdk', []);
app.controller('MenuItemController', function ($scope, $http) {
    $scope.processForm = function () {
        $http.post('/menuItems', JSON.stringify($scope.formData))
            .success(function (data) {
                console.log(data);
            });
    };
});
})();

我想我已经为所有事物加了圆顶,但显然没有。我还尝试在server.js中安装和使用“ body-paarser”,但结果相同。

当我的服务器崩溃时,它会像这样转储:

{ _readableState: 
   { highWaterMark: 16384,
     buffer: [],
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: false,
     ended: false,
     endEmitted: false,
     reading: false,
     calledRead: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     objectMode: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: false,
     oldMode: false,
     decoder: null,
     encoding: null },
  readable: true,
  domain: null,
  _events: {},
  _maxListeners: 10,
  socket: 
   { _connecting: false,
     _handle: 
      { fd: null,
        writeQueueSize: 0,
        owner: [Circular],
        onread: [Function: onread],
        reading: true },
     _readableState: 
      { highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: false,
        ended: false,
        endEmitted: false,
        reading: true,
        calledRead: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        objectMode: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        oldMode: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _events: 
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        drain: [Object],
        timeout: [Function],
        error: [Object],
        close: [Object] },
     _maxListeners: 10,
     _writableState: 
      { highWaterMark: 16384,
        objectMode: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [],
        errorEmitted: false },
     writable: true,
     allowHalfOpen: true,
     onend: [Function],
     destroyed: false,
     bytesRead: 2496,
     _bytesDispatched: 157759,
     _pendingData: null,
     _pendingEncoding: '',
     server: 
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        _connections: 6,
        connections: [Getter/Setter],
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        allowHalfOpen: true,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _connectionKey: '4:0.0.0.0:3000' },
     _idleTimeout: 120000,
     _idleNext: 
      { _connecting: false,
        _handle: [Object],
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        onend: [Function],
        destroyed: false,
        bytesRead: 375,
        _bytesDispatched: 1410,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Circular],
        _idleStart: 1406644394348,
        parser: [Object],
        ondata: [Function],
        _paused: false,
        _httpMessage: null },
     _idlePrev: { _idleNext: [Circular], _idlePrev: [Object] },
     _idleStart: 1406644399010,
     parser: 
      { _headers: [],
        _url: '',
        onHeaders: [Function: parserOnHeaders],
        onHeadersComplete: [Function: parserOnHeadersComplete],
        onBody: [Function: parserOnBody],
        onMessageComplete: [Function: parserOnMessageComplete],
        socket: [Circular],
        incoming: [Circular],
        maxHeaderPairs: 2000,
        onIncoming: [Function] },
     ondata: [Function],
     _paused: false,
     _httpMessage: 
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        output: [],
        outputEncodings: [],
        writable: true,
        _last: false,
        chunkedEncoding: false,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: true,
        sendDate: true,
        _headerSent: false,
        _header: '',
        _hasBody: true,
        _trailer: '',
        finished: false,
        _hangupClose: false,
        socket: [Circular],
        connection: [Circular],
        _headers: [Object],
        _headerNames: [Object],
        req: [Circular],
        locals: {} } },
  connection: 
   { _connecting: false,
     _handle: 
      { fd: null,
        writeQueueSize: 0,
        owner: [Circular],
        onread: [Function: onread],
        reading: true },
     _readableState: 
      { highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: false,
        ended: false,
        endEmitted: false,
        reading: true,
        calledRead: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        objectMode: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        oldMode: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _events: 
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        drain: [Object],
        timeout: [Function],
        error: [Object],
        close: [Object] },
     _maxListeners: 10,
     _writableState: 
      { highWaterMark: 16384,
        objectMode: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [],
        errorEmitted: false },
     writable: true,
     allowHalfOpen: true,
     onend: [Function],
     destroyed: false,
     bytesRead: 2496,
     _bytesDispatched: 157759,
     _pendingData: null,
     _pendingEncoding: '',
     server: 
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        _connections: 6,
        connections: [Getter/Setter],
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        allowHalfOpen: true,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _connectionKey: '4:0.0.0.0:3000' },
     _idleTimeout: 120000,
     _idleNext: 
      { _connecting: false,
        _handle: [Object],
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        onend: [Function],
        destroyed: false,
        bytesRead: 375,
        _bytesDispatched: 1410,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Circular],
        _idleStart: 1406644394348,
        parser: [Object],
        ondata: [Function],
        _paused: false,
        _httpMessage: null },
     _idlePrev: { _idleNext: [Circular], _idlePrev: [Object] },
     _idleStart: 1406644399010,
     parser: 
      { _headers: [],
        _url: '',
        onHeaders: [Function: parserOnHeaders],
        onHeadersComplete: [Function: parserOnHeadersComplete],
        onBody: [Function: parserOnBody],
        onMessageComplete: [Function: parserOnMessageComplete],
        socket: [Circular],
        incoming: [Circular],
        maxHeaderPairs: 2000,
        onIncoming: [Function] },
     ondata: [Function],
     _paused: false,
     _httpMessage: 
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        output: [],
        outputEncodings: [],
        writable: true,
        _last: false,
        chunkedEncoding: false,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: true,
        sendDate: true,
        _headerSent: false,
        _header: '',
        _hasBody: true,
        _trailer: '',
        finished: false,
        _hangupClose: false,
        socket: [Circular],
        connection: [Circular],
        _headers: [Object],
        _headerNames: [Object],
        req: [Circular],
        locals: {} } },
  httpVersion: '1.1',
  complete: false,
  headers: 
   { host: 'localhost:3000',
     connection: 'keep-alive',
     'content-length': '19',
     accept: 'application/json, text/plain, */*',
     origin: 'http://localhost:3000',
     'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36',
     'content-type': 'application/json;charset=UTF-8',
     referer: 'http://localhost:3000/admin/',
     'accept-encoding': 'gzip,deflate,sdch',
     'accept-language': 'en,da;q=0.8,nb;q=0.6,sv;q=0.4' },
  trailers: {},
  _pendings: [],
  _pendingIndex: 0,
  url: '/menuItems',
  method: 'POST',
  statusCode: null,
  client: 
   { _connecting: false,
     _handle: 
      { fd: null,
        writeQueueSize: 0,
        owner: [Circular],
        onread: [Function: onread],
        reading: true },
     _readableState: 
      { highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: false,
        ended: false,
        endEmitted: false,
        reading: true,
        calledRead: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        objectMode: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        oldMode: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _events: 
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        drain: [Object],
        timeout: [Function],
        error: [Object],
        close: [Object] },
     _maxListeners: 10,
     _writableState: 
      { highWaterMark: 16384,
        objectMode: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [],
        errorEmitted: false },
     writable: true,
     allowHalfOpen: true,
     onend: [Function],
     destroyed: false,
     bytesRead: 2496,
     _bytesDispatched: 157759,
     _pendingData: null,
     _pendingEncoding: '',
     server: 
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        _connections: 6,
        connections: [Getter/Setter],
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        allowHalfOpen: true,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _connectionKey: '4:0.0.0.0:3000' },
     _idleTimeout: 120000,
     _idleNext: 
      { _connecting: false,
        _handle: [Object],
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        onend: [Function],
        destroyed: false,
        bytesRead: 375,
        _bytesDispatched: 1410,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Circular],
        _idleStart: 1406644394348,
        parser: [Object],
        ondata: [Function],
        _paused: false,
        _httpMessage: null },
     _idlePrev: { _idleNext: [Circular], _idlePrev: [Object] },
     _idleStart: 1406644399010,
     parser: 
      { _headers: [],
        _url: '',
        onHeaders: [Function: parserOnHeaders],
        onHeadersComplete: [Function: parserOnHeadersComplete],
        onBody: [Function: parserOnBody],
        onMessageComplete: [Function: parserOnMessageComplete],
        socket: [Circular],
        incoming: [Circular],
        maxHeaderPairs: 2000,
        onIncoming: [Function] },
     ondata: [Function],
     _paused: false,
     _httpMessage: 
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        output: [],
        outputEncodings: [],
        writable: true,
        _last: false,
        chunkedEncoding: false,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: true,
        sendDate: true,
        _headerSent: false,
        _header: '',
        _hasBody: true,
        _trailer: '',
        finished: false,
        _hangupClose: false,
        socket: [Circular],
        connection: [Circular],
        _headers: [Object],
        _headerNames: [Object],
        req: [Circular],
        locals: {} } },
  _consuming: false,
  _dumped: false,
  httpVersionMajor: 1,
  httpVersionMinor: 1,
  upgrade: false,
  next: [Function: next],
  baseUrl: '',
  originalUrl: '/menuItems',
  _parsedUrl: 
   { protocol: null,
     slashes: null,
     auth: null,
     host: null,
     port: null,
     hostname: null,
     hash: null,
     search: null,
     query: null,
     pathname: '/menuItems',
     path: '/menuItems',
     href: '/menuItems' },
  params: {},
  query: {},
  res: 
   { domain: null,
     _events: { finish: [Function] },
     _maxListeners: 10,
     output: [],
     outputEncodings: [],
     writable: true,
     _last: false,
     chunkedEncoding: false,
     shouldKeepAlive: true,
     useChunkedEncodingByDefault: true,
     sendDate: true,
     _headerSent: false,
     _header: '',
     _hasBody: true,
     _trailer: '',
     finished: false,
     _hangupClose: false,
     socket: 
      { _connecting: false,
        _handle: [Object],
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        onend: [Function],
        destroyed: false,
        bytesRead: 2496,
        _bytesDispatched: 157759,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 1406644399010,
        parser: [Object],
        ondata: [Function],
        _paused: false,
        _httpMessage: [Circular] },
     connection: 
      { _connecting: false,
        _handle: [Object],
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        onend: [Function],
        destroyed: false,
        bytesRead: 2496,
        _bytesDispatched: 157759,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 1406644399010,
        parser: [Object],
        ondata: [Function],
        _paused: false,
        _httpMessage: [Circular] },
     _headers: { 'x-powered-by': 'Express' },
     _headerNames: { 'x-powered-by': 'X-Powered-By' },
     req: [Circular],
     locals: {} },
  route: 
   { path: '/menuItems',
     stack: [ [Object] ],
     methods: { post: true } } }
vodolaz095

您需要使用https://www.npmjs.org/package/body-parser模块来解析POST请求的正文。

app.use(express.static(__dirname));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.get('/menuItems', menu.getMenuItems);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Travis变量在node.js中不可用

来自分类Dev

如何使用node.js读取请求请求有效负载并进行表达?

来自分类Dev

当 Mule 不可用时,将请求有效负载映射到变量会引发异常

来自分类Dev

在vbscript中带有请求标头和有效负载的POST CURL

来自分类Dev

如何从POST请求有效负载中提取特定信息并保存到txt文件中?

来自分类Dev

通过代码设置的env变量在node.js中的导入模块中不可用

来自分类Dev

在GWT RPC调用中编码请求有效负载

来自分类Dev

.NET Core 3中的日志请求有效负载

来自分类Dev

Typhoeus Ruby 删除请求中的有效负载

来自分类Dev

div的翻转内容在Firefox上有效,但在Chrome中不可用

来自分类Dev

preventDefault for save popup在chrome中有效,但在Firefox中不可用

来自分类Dev

代码在Xamarin Android上有效,但在Java(HttpPost JSON)中不可用

来自分类Dev

cURL在cli上有效,但在php中不可用

来自分类Dev

$ .ajax.done在Firefox上有效,但在Chrome中不可用

来自分类Dev

CSS剪切路径在Firefox中有效,但在chrome中不可用

来自分类Dev

$ _POST未填充有效负载中显示的数据

来自分类Dev

在AngularJs POST调用中构造有效负载

来自分类Dev

来自ajax请求的值不可用

来自分类Dev

HTTP协议中POST请求/响应正文的有效负载的最大限制是多少?通过REST发送JSON

来自分类Dev

请求的资源在Spring MVC中不可用

来自分类Dev

所请求的资源在REST中不可用

来自分类Dev

在一个路由文件中定义的Express-session在app.js Node JS中不可用

来自分类Dev

请求的资源不可用?

来自分类Dev

预订系统有效的方法,使房间不可用

来自分类Dev

有没有办法在套件的不同测试用例中模拟来自相同缓存范围的 HTTP 请求的有效负载?

来自分类Dev

通过使用scrapy中的请求有效负载来发布请求

来自分类Dev

通过github.io部署时,jQuery在Codeacademy上有效,但在Firefox中不可用

来自分类Dev

使用jQuery选择数据属性-在Chrome浏览器中有效,而在Firefox中不可用。选择?

来自分类Dev

VIM语法高亮显示在MacVim中有效,但在终端中不可用vi吗?

Related 相关文章

  1. 1

    Travis变量在node.js中不可用

  2. 2

    如何使用node.js读取请求请求有效负载并进行表达?

  3. 3

    当 Mule 不可用时,将请求有效负载映射到变量会引发异常

  4. 4

    在vbscript中带有请求标头和有效负载的POST CURL

  5. 5

    如何从POST请求有效负载中提取特定信息并保存到txt文件中?

  6. 6

    通过代码设置的env变量在node.js中的导入模块中不可用

  7. 7

    在GWT RPC调用中编码请求有效负载

  8. 8

    .NET Core 3中的日志请求有效负载

  9. 9

    Typhoeus Ruby 删除请求中的有效负载

  10. 10

    div的翻转内容在Firefox上有效,但在Chrome中不可用

  11. 11

    preventDefault for save popup在chrome中有效,但在Firefox中不可用

  12. 12

    代码在Xamarin Android上有效,但在Java(HttpPost JSON)中不可用

  13. 13

    cURL在cli上有效,但在php中不可用

  14. 14

    $ .ajax.done在Firefox上有效,但在Chrome中不可用

  15. 15

    CSS剪切路径在Firefox中有效,但在chrome中不可用

  16. 16

    $ _POST未填充有效负载中显示的数据

  17. 17

    在AngularJs POST调用中构造有效负载

  18. 18

    来自ajax请求的值不可用

  19. 19

    HTTP协议中POST请求/响应正文的有效负载的最大限制是多少?通过REST发送JSON

  20. 20

    请求的资源在Spring MVC中不可用

  21. 21

    所请求的资源在REST中不可用

  22. 22

    在一个路由文件中定义的Express-session在app.js Node JS中不可用

  23. 23

    请求的资源不可用?

  24. 24

    预订系统有效的方法,使房间不可用

  25. 25

    有没有办法在套件的不同测试用例中模拟来自相同缓存范围的 HTTP 请求的有效负载?

  26. 26

    通过使用scrapy中的请求有效负载来发布请求

  27. 27

    通过github.io部署时,jQuery在Codeacademy上有效,但在Firefox中不可用

  28. 28

    使用jQuery选择数据属性-在Chrome浏览器中有效,而在Firefox中不可用。选择?

  29. 29

    VIM语法高亮显示在MacVim中有效,但在终端中不可用vi吗?

热门标签

归档