![](/img/trans.png)
[英](node:23) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
[英](node:45207) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]
我正在通過構建一個簡單的代碼片段應用程序來學習 Node.js。 它將有兩個字段title
和snippet
。 在提交新代碼段時,我不斷收到如下錯誤。
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:535:11)
at ServerResponse.header (/myportal/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/myportal/node_modules/express/lib/response.js:170:12)
at /myportal/routes/index.js:99:36
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
(node:45207) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:535:11)
at ServerResponse.header (/myportal/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/myportal/node_modules/express/lib/response.js:170:12)
at /myportal/routes/index.js:102:25
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:45207) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:45207) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
const express = require( "express" );
const mongoose = require( 'mongoose' );
const router = express.Router();
const snippetSchema = mongoose.model( 'snippetSchema' );
const { check, validationResult } = require( 'express-validator' );
router.post( '/newsnippet',
[
check( 'title' )
.isLength( { min: 1 } )
.withMessage( ' Please enter a valid title name.' ),
check( 'snippet' )
.isLength( { min: 1 } )
.withMessage( ' Please enter a valid snippet.' ),
],
( req, res ) => {
const errors = validationResult( req );
if ( errors.isEmpty() ) {
res.send( "Thank you for adding new snippet." );
console.log( "Req Body : " + JSON.stringify( req.body ) );
const newSnippet = new snippetSchema( req.body );
console.log( " I am executed till creating newSnippet instantiation" + JSON.stringify( newSnippet ) );
newSnippet.save()
.then( () => { res.send( 'Thank you for adding new snippet :)' ); console.log( "Reached till here!" ) } )
.catch( ( err ) => {
console.log( err );
res.send( 'Sorry! something went wrong' );
} );
//return;
} else {
res.render( 'snippets', {
title: "My Homepage",
errors: errors.array(),
data: req.body,
} );
//return;
}
}
);
module.exports = router;
const mongoose = require( 'mongoose' );
mongoose.set( 'useCreateIndex', true );
const snippetSchema = new mongoose.Schema( {
title: {
type: String,
trim: true,
//unique: true,
},
snippet_code: {
type: String,
trim: true,
//unique: true,
}
} );
module.exports = mongoose.model( 'snippetSchema', snippetSchema );
還有一個觀察結果是,即使我的 model 在啟動新的 model object 時有兩個字段,例如title
和snippet
,我也沒有得到我的片段字段。
調試日志如下
Req Body : {"title":"Create New Change","snippet":"var r = new Record(); var result = r.createChange({\"short_description\" :\"Sample Changee\"}); print.info(result.number);"}
I am executed till creating newSnippet instantiation{"_id":"5ea5195c9fcbc0b10ebd7968","title":"Create New Change"}
我搜索了 stackoverflow 並發現錯誤-無法設置標頭-在它們被發送到客戶端后但無法理解。
任何建議,非常感謝。
謝謝你。
您不能為同一請求發送兩次響應。
router.post( '/newsnippet',
[
check( 'title' )
.isLength( { min: 1 } )
.withMessage( ' Please enter a valid title name.' ),
check( 'snippet' )
.isLength( { min: 1 } )
.withMessage( ' Please enter a valid snippet.' ),
],
( req, res ) => {
const errors = validationResult( req );
if ( errors.isEmpty() ) {
const newSnippet = new snippetSchema( req.body );
console.log( " I am executed till creating newSnippet instantiation" + JSON.stringify( newSnippet ) );
newSnippet.save()
.then( () => { res.send( 'Thank you for adding new snippet :)' ); console.log( "Reached till here!" ) } )
.catch( ( err ) => {
console.log( err );
res.send( 'Sorry! something went wrong' );
} );
永遠記住,只有在發送響應后嘗試設置標頭時,才會在節點中發生此錯誤。
因此,在調試時查找res.send()
。
這兩個是不一樣的。
router.get('/', async(req, res) => {
return res.send('Hello world');
res.send('Thanks for adding code snippet')!; // this line will not be executed, no errors
);
router.get('/', async(req, res) => {
res.send('Hello world');
res.send('Thanks for adding code snippet')!; // this line will be executed, and cause errors
);
next()
也是如此。 next()
將導致代碼繼續執行,而return next()
將停止執行並調用下一個中間件。
更多在頂部。 當您從middleware
function return res.send()
時,它將跳過所有其他中間件,並返回響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.