首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >(节点:45207) UnhandledPromiseRejectionWarning: ERR_HTTP_HEADERS_SENT [ERR_HTTP_HEADERS_SENT]

(节点:45207) UnhandledPromiseRejectionWarning: ERR_HTTP_HEADERS_SENT [ERR_HTTP_HEADERS_SENT]
EN

Stack Overflow用户
提问于 2020-04-26 05:28:07
回答 1查看 125关注 0票数 0

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

代码语言:javascript
复制
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

代码语言:javascript
复制
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;

模型码

代码语言:javascript
复制
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,但是我没有得到我的代码片段字段。

调试日志如下所示

代码语言:javascript
复制
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"}

我搜索了堆栈溢出,发现了error-cant-set-headers-after-they-are-sent-to-the-client,但无法理解。

任何建议,都非常感谢。

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-26 05:37:53

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

代码语言:javascript
复制
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()

这两者是不一样的。

代码语言:javascript
复制
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()将停止执行并调用下一个中间件。

更多关于最上面的内容。当您从一个return res.send()函数进行middleware时,它将跳过所有其他的中间件,并返回响应。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61436214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档