gpt4 book ai didi

javascript - ( Node :45207) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]

转载 作者:行者123 更新时间:2023-12-02 20:57:34 27 4
gpt4 key购买 nike

我正在通过构建一个简单的代码片段应用程序来学习 Node.js。它将有两个字段 titlesnippet。在提交新代码片段时,我不断收到如下错误。

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.

index.js

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 );

还有一个观察结果是,即使我的模型在启动新模型对象时有两个字段,例如 titlesnippet,但我没有得到我的代码段字段。

调试日志如下

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 并发现 error-cant-set-headers-after-they-are-sent-to-the-client但无法理解。

任何建议,非常感谢。

谢谢。

最佳答案

您不能对同一请求发送两次响应。

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' );

} );

永远记住,当您在发送响应后尝试设置 header 时,此错误仅发生在 Node 中。

因此,在调试时查找 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() 将停止执行并调用下一个中间件。

更多关于主题。 当您从中间件函数返回res.send()时,它将跳过所有其他中间件,并返回响应。

关于javascript - ( Node :45207) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61436214/

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