错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头

Posted

技术标签:

【中文标题】错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头【英文标题】:Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 【发布时间】:2018-09-19 07:27:09 【问题描述】:

所以我看到了这篇很棒的帖子 Error: Can't set headers after they are sent to the client ,但仍然不明白,我的标题部分出了什么问题,因为当我将它从我的 commented out 错误类型更改为两个单独的部分时:app.use(doesNotModifyBody); app.use(doesModifyBody);(如上面的答案)它无法正常工作。

现在,我总是从app.use(doesModifyBody); - res.write("<p>Hello World</p>"); 中提取字符串,而不是接收正确的数据库答案。

所以问题是,如何解决问题标题中标题的错误并使正确的数据库答案接收,而不是res.write("<p>Hello World</p>"); P.S.删除res.write("<p>Hello World</p>"); 并不能解决问题。

我的服务器代码:

'use strict'
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const router = express.Router();
const EmployersSchemaDB = require('./SchemaDB/EmployersSchemaDB');

mongoose.connect('mongodb://myDB');

app.use(bodyParser.urlencoded( extended: true ));
app.use(bodyParser.json());

// app.use((req, res, next) => 
//     res.setHeader('Access-Control-Allow-Origin', '*');
//     res.setHeader('Access-Control-Allow-Credentials', 'true');
//     res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
//     res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
//     res.setHeader('Cache-Control', 'no-cache');
//     next();
// ); I change this on:

let doesNotModifyBody = (req, res, next) => 
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
    res.setHeader('Cache-Control', 'no-cache');
    next();
  ; // this 
let doesModifyBody = (req, res, next) => 
    res.setHeader("Content-Type", "text/html");
    res.write("<p>Hello World</p>");
    res.end();
  ; // and this

app.use(doesNotModifyBody);
app.use(doesModifyBody);

router.get('/', (req, res) => 
    res.json( message: 'Server is Initialized!');
);

router.route('/employers')
    .get((req, res) => 
        EmployersSchemaDB.find((err, employers) => 
            if (err)  res.send(err) 

            res.json(employers);
        );
    )
    .post((req, res) => 
        let employer = new EmployersSchemaDB();

        employer.first_name = req.body.first_name;
        employer.last_name = req.body.last_name;
        employer.birth_date = req.body.birth_date;
        employer.salary = req.body.salary;

        employer.save((err) => 
            if (err)  res.send(err) 

            res.json( message: 'Comment successfully added!', employer );
            console.log('---===--- \n Employer added: \n', employer + '\n ---===---');
        );  
    );

router.route('/employers/:employer_id')
    .get((req, res) => 
        EmployersSchemaDB.findById(req.params.employer_id, (err, employer) => 
            if (err)  res.send(err) 

            res.json( message: 'Employer has been getted', employer: employer );
        );
    )
    .put((req, res) => 
        EmployersSchemaDB.findById(req.params.employer_id, (err, employer) => 
            if (err)  res.send(err) 

            (req.body.id) ? employer.id = req.body.id : null;
            (req.body.first_name) ? employer.first_name = req.body.first_name : null;
            (req.body.last_name) ? employer.last_name = req.body.last_name : null;
            (req.body.birth_date) ? employer.birth_date = req.body.birth_date : null;
            (req.body.salary) ? employer.salary = req.body.salary : null;

            employer.save((err) => 
                if (err)  res.send(err) 

                res.json( message: 'Employer has been updated', employer: employer  );
            );
        );
    )
    .delete((req, res) => 
        EmployersSchemaDB.remove( _id: req.params.employer_id , (err, employer) => 
            if (err)  res.send(err) 

            res.json( message: 'Comment has been deleted' )
        )
    );

app.use('/', router);

const port = process.env.API_PORT || 3016;
app.listen(port, () => 
    console.log(`Server running on port $port`);
);

【问题讨论】:

【参考方案1】:

问题是你在打电话

res.write("<p>Hello World</p>");
res.end();

它将响应发送回客户端。完成此操作后,您将无法发送任何进一步的数据。您尝试通过在中间件中调用 res.json() 来做到这一点,这就是您想要得到错误的原因;

删除 res.endres.write 行,它应该可以工作。

【讨论】:

不,它不起作用。您没有完全阅读我的问题:P.S.删除 res.write("

Hello World

");并不能解决问题。
我确实阅读了您的问题。你谈到了删除res.write。你还需要删除res.end

以上是关于错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头的主要内容,如果未能解决你的问题,请参考以下文章

为啥我不断收到“错误 [ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头”错误?

错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法删除标头

Express.js 中的新 Mongoose Schema `ERR_HTTP_HEADERS_SENT` 错误

Firebase - Node.js - Express - 错误 [ERR_HTTP_HEADERS_SENT]

错误 [ERR_HTTP_HEADERS_SENT] 在将标头发送到客户端后无法设置标头

错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头