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

2024-04-21

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

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

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

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

服务器.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 } } }

你需要使用https://www.npmjs.org/package/body-parser 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

来自 post 请求的有效负载在 Node.js 函数中不可用 的相关文章

  • Typescript 和 Mongoose - “this”在实例方法中不可用

    我目前正在将我的 API 从 JS 转换为 TS 然而 我在猫鼬和打字稿方面遇到了一些困难 具体来说 this在我的实例方法中不可用 My code AccountSchema methods comparePassword async f
  • 使用admin sdk在云函数中执行firestore集合组查询?

    firestore collectionGroup 方法在云函数中与 firebase admin sdk 一起使用时出现错误 是否可以在云函数中对 firestore 进行集合组查询 这是我尝试使用的 firestore 查询方法 htt
  • 如何从控制器返回 PDF 文件

    我正在尝试使用 NestJs 从控制器端点返回 PDF 文件 未设置时Content typeheader 返回的数据getDocumentFile 很好地返回给用户 然而 当我添加标头时 我得到的返回似乎是某种奇怪形式的 GUID 响应总
  • Nodejs - 处理和发送多部分请求,

    我的应用程序在 Nodejs 服务器上运行 Node Js 还充当来自应用程序的请求的中间件 代理 因此 从浏览器开始 所有 REST 调用都会转到 NodeJs 然后转到 Java API 我发现处理多部分表单数据的请求时出现问题 我在
  • Visual Studio 代码断点在使用 TypeScript 的 Node.js 上不起作用

    我尝试了很多解决方案 但没有人适合我 代码执行 但我无法放置断点并调试它 请你帮助我好吗 我尝试过以下 VSCode 配置脚本 type node request launch name Typescript Node JS program
  • Angularjs 手表服务对象

    为什么我无法观看服务中的对象 我有一个简单的变量可以工作 但是一个对象不能工作 http plnkr co edit S4b2g3baS7dwQt3t8XEK p preview http plnkr co edit S4b2g3baS7d
  • Swagger 生成 javascript-closure-angular-client

    我是 swagger 的新手 我从 swagger 的在线编辑器生成了一个 javascript 闭包角度客户端 它给了我一个 DefaultAPI js 和其他与我的对象定义匹配的 JS 文件 我在 swagger 文档和网上搜索了一种在
  • 如何使用 Nodejs 创建 Excel 文件?

    我是一名 Nodejs 程序员 现在我有一个数据表 我想将其保存为 Excel 文件格式 我该怎么做呢 我找到了一些 Node 库 但其中大多数是 Excel 解析器而不是 Excel 编写器 我使用的是 Linux 服务器 因此需要一些可
  • BUG - 在 IOS 中没有选择标签的完成按钮

    我正在使用最新的离子并有一个简单的选择标签
  • Mongodb更新很多

    我正在使用express js 和 npm 模块 mongodb 进行开发 并以 mongodb 作为数据库 我有两个集合 即 用户 和 活动 一个用户可能有数千个活动 首先 我将用户的 id 姓名和图片 url 存储到 关系的活动文件 请
  • 导航嵌套组件时创建面包屑 (Angular 2)

    我正在为此苦苦挣扎 这个想法是有一个组件 当浏览子视图时更新面包屑 例如
  • 如何在angularjs中使用addClass方法

    我有一个仅限于类的 angularjs 指令 如何使用 angularjs 中的 addClass 方法添加它 指示 app directive number function return restrict C link function
  • 重写规则,以便正确加载具有绝对路径的 css 和 js 文件

    我花了两个小时 但我无法弄清楚 我不知道如何谷歌解决方案 这是我在 htaccess 文件中的重写规则 RewriteCond REQUEST URI blog RewriteRule blog http localhost 2368 1
  • 如何将 Gulp 添加到我的项目中?

    我正在使用 Windows 7 Visual Studio 2013 我正在尝试在我的客户项目中设置 Gulp 我已将这些 Nuget 添加到项目中 Node js 版本 0 12 0 Npm js 版本 1 3 15 10 由于某种原因我
  • Angular UI 模式的范围问题

    我无法理解 使用角度 UI 模式的范围 虽然这里不是很明显 但我已经正确设置了模块和所有内容 据我所知 但这些代码示例尤其是我发现错误的地方 index html 其中重要部分 div class btn group div
  • 如何正确清理来自 AngularJS 控制器的无效输入的表单?

    我有一个 AngularJS 表单 其中包含 除其他字段之外 类型之一url 后者很重要 因为这会强制相应的输入成为有效的 URL 在某些条件下 例如 要关闭具有此类表单的模式对话框 我想以编程方式清除该表单 为此 我实现了方法reset基
  • 使用 AWS CDK 为 lambda 指定自定义角色

    我意识到它很新 但我没有看到任何语言的任何示例 说明如何为使用 AWS CDK 创建的 lambda 指定角色 我正在尝试这样做 const cdk require aws cdk cdk const lambda require aws
  • 如何在Sequelize中设置查询超时?

    我想看看如何在 Sequelize 中设置查询的超时时间 我查看了 Sequelize 文档以获取一些信息 但我找不到我要找的东西 我发现的最接近的是 pools acquire 选项 但我不想设置传入连接的超时 而是设置正在进行的查询的超
  • 带有 npm 启动脚本的 Nodejs 应用程序

    我对nodejs很陌生 在我的docker化环境中 我想为nodejs应用程序提供appdynamics支持 这要求每个应用程序都要求将以下内容作为其应用程序的第一行 require appdynamics profile controll
  • 如何处理 MongoDB 的断开连接错误

    我在 Node js 进程中看到了这个未捕获的异常 Uncaught exception Error read ETIMEDOUT at TCP onStreamRead internal stream base commons js 16

随机推荐