gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 23:00:48 27 4
gpt4 key购买 nike

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

我想要完成的是让一个简单的表单提交一个值并将该值写入数据库。我已经到了在我的 Angular 应用程序中使用 $http.post 提交我的值的地步,我确实调用了我的 node.js 后端函数,但我的 req 参数(下面的 se)未定义。从 Google Chromes 网络监视器中,我可以看到提交了一个 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);
});

菜单.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]);
}
});
});

};

应用程序.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模块来解析 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);

关于node.js - 来自 post 请求的负载在 node.js 函数中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25019007/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com