错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后,无法设置标头 [英] Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

查看:356
本文介绍了错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后,无法设置标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我看到了这篇很棒的帖子错误:将标头发送给客户端后无法设置标头,但仍然不明白,标头部分出了什么问题,因为当我将其从commented out错误类型更改为两个单独的部分时,
app.use(doesNotModifyBody); app.use(doesModifyBody);(就像上面的答案一样),它无法正常工作.

So I saw this great post Error: Can't set headers after they are sent to the client , but still do not understand, what is wrong with my Headers section, because when I changed it from my commented out wrong type into two separated sections:
app.use(doesNotModifyBody); app.use(doesModifyBody); (like in answer above) it does not work normally.

现在,我始终没有收到正确的数据库答案,而是总是从app.use(doesModifyBody);-res.write("<p>Hello World</p>");保留字符串.

And for now, instead of receiving the right database answer, I always resive the string from the app.use(doesModifyBody); - res.write("<p>Hello World</p>");.

问题是,如何解决问题标题中的标题,并正确记录数据库答案,而不是res.write("<p>Hello World</p>"); P.S.删除res.write("<p>Hello World</p>");是不能解决问题.

So the question, how to solve the error with the Headers in the question title and make right database answer receving, instead of res.write("<p>Hello World</p>"); P.S. deleting the res.write("<p>Hello World</p>"); is does not solve the problem.

我的服务器代码:

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

推荐答案

问题是您正在呼叫

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

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

Which sends the response back to the client. Once you do this you cannot send any further data. You try to do that by calling res.json() in your middleware, which is why you want get the error that you get;

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

Remove BOTH the res.end and res.write lines and it should work.

这篇关于错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后,无法设置标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆