如何将正文传递给表达路由器以获取 PUT 请求?
How to pass body to express router for PUT request?
我正在尝试使用 express.js 创建 PUT 请求,但我不断收到此错误,指出 body is not defined
。但是当我将 req
打印到控制台时,我确实看到 body
和数据。
快递
router.put('/category-statement/:corporate_statement_link_id', function(req, res){
console.log("req: ",req);
var reqBody = req.body;
var id = req.params.corporate_statement_link_id;
console.log("Body: ", body);
console.log("id:", id);
let sql = `UPDATE corporate_statements
SET corporate_statement = ? WHERE corporate_statement_link_id = ?`;
db.run(sql,[reqBody.corporate_statement, id], (err, row) =>{
if(err){
res.status(500).send(err);
}
res.send(row)
});
})
Angular 服务
updateCorporateStatementStatus(corporate_statement_link_id:number, corporate_statement:ICorporateStatementInfo){
console.log("corporate statement", corporate_statement);
const headers= new HttpHeaders()
.set('content-type', 'application/json')
.set('Access-Control-Allow-Origin', '*');
var body = corporate_statement; // copying to body thinking router.put is specifically looking for body
console.log(corporate_statement);
return this.http.put<ICorporateStatementInfo>('/api/v1/statements/category-statement/' + corporate_statement_link_id, body, {headers})
.subscribe(data => {
console.log(data);
})
}
请求打印
这只是 router.put
中 req
的一部分
params: { corporate_statement_link_id: '3' },
query: {},
res: ServerResponse {
_events: [Object: null prototype] {
finish: [Array],
end: [Function: onevent]
},
_eventsCount: 2,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
secureConnecting: false,
_SNICallback: null,
servername: 'localhost',
alpnProtocol: 'http/1.1',
authorized: false,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 11,
connecting: false,
_hadError: false,
_parent: [Socket],
_host: null,
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: true,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: null,
ssl: [TLSWrap],
_requestCert: false,
_rejectUnauthorized: true,
timeout: 120000,
parser: [HTTPParser],
on: [Function: socketListenerWrap],
addListener: [Function: socketListenerWrap],
prependListener: [Function: socketListenerWrap],
_paused: false,
_httpMessage: [Circular],
_peername: [Object],
[Symbol(res)]: [TLSWrap],
[Symbol(verified)]: false,
[Symbol(pendingSession)]: null,
[Symbol(asyncId)]: 19,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: 120000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 18664,
_onTimeout: [Function: bound ],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(refed)]: false,
[Symbol(asyncId)]: 977,
[Symbol(triggerId)]: 23
},
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(error-emitted)]: false
},
connection: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
secureConnecting: false,
_SNICallback: null,
servername: 'localhost',
alpnProtocol: 'http/1.1',
authorized: false,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 11,
connecting: false,
_hadError: false,
_parent: [Socket],
_host: null,
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: true,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: null,
ssl: [TLSWrap],
_requestCert: false,
_rejectUnauthorized: true,
timeout: 120000,
parser: [HTTPParser],
on: [Function: socketListenerWrap],
addListener: [Function: socketListenerWrap],
prependListener: [Function: socketListenerWrap],
_paused: false,
_httpMessage: [Circular],
_peername: [Object],
[Symbol(res)]: [TLSWrap],
[Symbol(verified)]: false,
[Symbol(pendingSession)]: null,
[Symbol(asyncId)]: 19,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: 120000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 18664,
_onTimeout: [Function: bound ],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(refed)]: false,
[Symbol(asyncId)]: 977,
[Symbol(triggerId)]: 23
},
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(error-emitted)]: false
},
_header: null,
_onPendingData: [Function: bound updateOutgoingData],
_sent100: false,
_expect_continue: false,
req: [Circular],
locals: [Object: null prototype] {},
_startAt: undefined,
_startTime: undefined,
writeHead: [Function: writeHead],
__onFinished: [Function: listener] { queue: [Array] },
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] { 'x-powered-by': [Array] }
},
_startAt: [ 267748, 220273300 ],
_startTime: 2020-10-19T01:47:48.684Z,
_remoteAddress: '::1',
body: { corporate_statement: false },
_body: true,
length: undefined,
route: Route {
path: '/category-statement/:corporate_statement_link_id',
stack: [ [Layer] ],
methods: { put: true }
},
[Symbol(kCapture)]: false
}
app.js
打印的错误
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
console.log(err.message);
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
console.log("this is where it's happening");
// render the error page
res.status(err.status || 500);
res.json({ error: err })
});
body is not defined
仔细查看您的代码。特别是你的 PUT
路线。
router.put('/category-statement/:corporate_statement_link_id', function(req, res){
console.log("req: ",req);
// You define `reqBody`...
var reqBody = req.body;
var id = req.params.corporate_statement_link_id;
// ...So where does `body` come from?
console.log("Body: ", body);
console.log("id:", id);
let sql = `UPDATE corporate_statements
SET corporate_statement = ? WHERE corporate_statement_link_id = ?`;
db.run(sql,[reqBody.corporate_statement, id], (err, row) =>{
if(err){
res.status(500).send(err);
}
res.send(row)
});
})
如您的代码所示,您定义了 reqBody
,并为其分配了 req.body
的值。然后,您尝试访问 (non-existent) 变量 body
。您可能打算输入 reqBody
.
我正在尝试使用 express.js 创建 PUT 请求,但我不断收到此错误,指出 body is not defined
。但是当我将 req
打印到控制台时,我确实看到 body
和数据。
快递
router.put('/category-statement/:corporate_statement_link_id', function(req, res){
console.log("req: ",req);
var reqBody = req.body;
var id = req.params.corporate_statement_link_id;
console.log("Body: ", body);
console.log("id:", id);
let sql = `UPDATE corporate_statements
SET corporate_statement = ? WHERE corporate_statement_link_id = ?`;
db.run(sql,[reqBody.corporate_statement, id], (err, row) =>{
if(err){
res.status(500).send(err);
}
res.send(row)
});
})
Angular 服务
updateCorporateStatementStatus(corporate_statement_link_id:number, corporate_statement:ICorporateStatementInfo){
console.log("corporate statement", corporate_statement);
const headers= new HttpHeaders()
.set('content-type', 'application/json')
.set('Access-Control-Allow-Origin', '*');
var body = corporate_statement; // copying to body thinking router.put is specifically looking for body
console.log(corporate_statement);
return this.http.put<ICorporateStatementInfo>('/api/v1/statements/category-statement/' + corporate_statement_link_id, body, {headers})
.subscribe(data => {
console.log(data);
})
}
请求打印
这只是 router.put
req
的一部分
params: { corporate_statement_link_id: '3' },
query: {},
res: ServerResponse {
_events: [Object: null prototype] {
finish: [Array],
end: [Function: onevent]
},
_eventsCount: 2,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
secureConnecting: false,
_SNICallback: null,
servername: 'localhost',
alpnProtocol: 'http/1.1',
authorized: false,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 11,
connecting: false,
_hadError: false,
_parent: [Socket],
_host: null,
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: true,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: null,
ssl: [TLSWrap],
_requestCert: false,
_rejectUnauthorized: true,
timeout: 120000,
parser: [HTTPParser],
on: [Function: socketListenerWrap],
addListener: [Function: socketListenerWrap],
prependListener: [Function: socketListenerWrap],
_paused: false,
_httpMessage: [Circular],
_peername: [Object],
[Symbol(res)]: [TLSWrap],
[Symbol(verified)]: false,
[Symbol(pendingSession)]: null,
[Symbol(asyncId)]: 19,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: 120000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 18664,
_onTimeout: [Function: bound ],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(refed)]: false,
[Symbol(asyncId)]: 977,
[Symbol(triggerId)]: 23
},
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(error-emitted)]: false
},
connection: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
secureConnecting: false,
_SNICallback: null,
servername: 'localhost',
alpnProtocol: 'http/1.1',
authorized: false,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 11,
connecting: false,
_hadError: false,
_parent: [Socket],
_host: null,
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: true,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: null,
ssl: [TLSWrap],
_requestCert: false,
_rejectUnauthorized: true,
timeout: 120000,
parser: [HTTPParser],
on: [Function: socketListenerWrap],
addListener: [Function: socketListenerWrap],
prependListener: [Function: socketListenerWrap],
_paused: false,
_httpMessage: [Circular],
_peername: [Object],
[Symbol(res)]: [TLSWrap],
[Symbol(verified)]: false,
[Symbol(pendingSession)]: null,
[Symbol(asyncId)]: 19,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: 120000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 18664,
_onTimeout: [Function: bound ],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(refed)]: false,
[Symbol(asyncId)]: 977,
[Symbol(triggerId)]: 23
},
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(error-emitted)]: false
},
_header: null,
_onPendingData: [Function: bound updateOutgoingData],
_sent100: false,
_expect_continue: false,
req: [Circular],
locals: [Object: null prototype] {},
_startAt: undefined,
_startTime: undefined,
writeHead: [Function: writeHead],
__onFinished: [Function: listener] { queue: [Array] },
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] { 'x-powered-by': [Array] }
},
_startAt: [ 267748, 220273300 ],
_startTime: 2020-10-19T01:47:48.684Z,
_remoteAddress: '::1',
body: { corporate_statement: false },
_body: true,
length: undefined,
route: Route {
path: '/category-statement/:corporate_statement_link_id',
stack: [ [Layer] ],
methods: { put: true }
},
[Symbol(kCapture)]: false
}
app.js
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
console.log(err.message);
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
console.log("this is where it's happening");
// render the error page
res.status(err.status || 500);
res.json({ error: err })
});
body is not defined
仔细查看您的代码。特别是你的 PUT
路线。
router.put('/category-statement/:corporate_statement_link_id', function(req, res){
console.log("req: ",req);
// You define `reqBody`...
var reqBody = req.body;
var id = req.params.corporate_statement_link_id;
// ...So where does `body` come from?
console.log("Body: ", body);
console.log("id:", id);
let sql = `UPDATE corporate_statements
SET corporate_statement = ? WHERE corporate_statement_link_id = ?`;
db.run(sql,[reqBody.corporate_statement, id], (err, row) =>{
if(err){
res.status(500).send(err);
}
res.send(row)
});
})
如您的代码所示,您定义了 reqBody
,并为其分配了 req.body
的值。然后,您尝试访问 (non-existent) 变量 body
。您可能打算输入 reqBody
.