在nodejs中发送标头后无法设置标头

Posted

技术标签:

【中文标题】在nodejs中发送标头后无法设置标头【英文标题】:Can't set headers after they are sent in nodejs 【发布时间】:2014-08-23 04:22:14 【问题描述】:

如何在 nodejs 中发送文件,我正在创建一个页面应用程序,所以我只想在第一次请求时交付 abcd.html 页面, 这是我的代码

app.js

var express = require('express'),
    app = express(), 
    http = require('http'), 
    path = require('path'),
    fs = require('fs'), 
    mysql = require('mysql'), 
    server = http.createServer(app),

    passport = require('passport'),
    flash    = require('connect-flash'),
    useragent = require('express-useragent'),
    io = require('socket.io').listen(server);

// configuration ===============================================================
    // connect to our database

    require('./config/passport')(passport); // pass passport for configuration

app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);



app.configure(function() 


    app.set('views', path.join(__dirname, 'app/views'));
    app.set('view engine', 'ejs'); // set up ejs for templating

    // required for passport
    app.use(express.session(secret: 'vidyapathaisalwaysrunning',key: 'myuser.sid',cookie:  secure: false,maxAge:null )); // session secret1
    //app.use(express.session(secret: 'vidyapathaisalwaysrunning', key: 'myownsid', cookie:  secure: false, maxAge: 3600000  )); // session with expitation 
    //app.use(express.session( key: 'express.sid', secret: 'vidyapathaisalwaysrunning'  )); // 2 cookieId ie connect.sid & express.sid(user defined) session secret1
    //app.use(express.session(  store: sessionStore, secret: 'vidyapathaisalwaysrunning',cookie: httpOnly: false,key: 'cookie.sid'  )); // session secret
    // set up our express application
    app.use(express.logger('dev')); // log every request to the console
    app.use(express.cookieParser()); // read cookies (needed for auth)
    app.use(express.bodyParser()); // get information from html forms
    app.use(useragent.express());
    app.use(express.json());
    app.use(express.urlencoded());
    app.use(express.methodOverride());  
    app.use(passport.initialize());
    app.use(passport.session()); // persistent login sessions
    app.use(flash()); // use connect-flash for flash messages stored in session
    app.use(express.static(path.join(__dirname, 'public')));
);

// development only
if ('development' == app.get('env')) 
  app.use(express.errorHandler());



//routes ======================================================================
require('./app/controller.js')(app, passport,io); // load our routes and pass in our app and fully configured passport
//require('./app/socket')(app,io);
// launch ======================================================================
server.listen(8080);

响应页面

case '/':
                    /*response.writeHead(200, 'Content-Type': 'text/html');
                    response.write('hello world');*/
                    //response.json( message: 'hello' );
                    response.sendfile("../public/abcd.html");

                    break;

发送后总是给出 Can't set headers,这里是控制台输出

错误:禁止 在 SendStream.error (/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/node_modules/send/lib/send.js:145:16) 在 SendStream.pipe (/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/node_modules/send/lib/send.js:307:39) 在 ServerResponse.res.sendfile (/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/lib/response.js:339:8) 在/home/pitu/CODING/NODE-PROJECTS/chichat/app/controller.js:18:21 在回调(/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/lib/router/index.js:161:37) 在参数(/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/lib/router/index.js:135:11) 通过(/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/lib/router/index.js:142:5) 在 Router._dispatch (/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/lib/router/index.js:170:5) 在 Object.router (/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/lib/router/index.js:33:10) 在下一个(/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/node_modules/connect/lib/proto.js:190:15) _http_outgoing.js:331 throw new Error('Can\'t set headers after they are sent.'); ^ 错误:发送后无法设置标题。 在 ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:331:11) 在 ServerResponse.res.setHeader (/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/node_modules/connect/lib/patch.js:59:22) 在/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js:63:17 在 fs.js:292:14 在 Object.oncomplete (fs.js:93:15)

参考截图 怎么办

【问题讨论】:

您确定不会因为.. 中使用的response.sendfile("../public/abcd.html"); 而遇到问题吗?更多信息:***.com/questions/14594121/… 【参考方案1】:
var event= require('./models/event');
var url = require('url');
var fs = require("fs");
//var app1 = require('../../app').app;
module.exports = function(app, passport,io)

    //app.get('/createevent',event.createevent);
    app.get('*', function(request, response) 
            
            var path = url.parse(request.url).pathname;
            //use request object to get user data
                //response.render('index');
                switch(path)
                case '/':
                    /*response.writeHead(200, 'Content-Type': 'text/html');
                    response.write('hello world');*/
                    //response.json( message: 'hello' );
                    //response.sendfile('../../public/abcd.htm', root: __dirname )
                    response.sendfile('./public/abcd.htm');

                    break;
                case '/creteevent':
                    console.log(" inside createevent ");
                    response.render('index123', title: 'The index page!' );
                    break;
                case '/eventmember':
                    //response.render('index');
                    //this method is good becz below code , calling same as 4 both socket & http req 
                    event.eventmember(function(err,returnedvalue)
                        
                          if(returnedvalue)
                           console.log(" member result "+returnedvalue);
                           response.json(returnedvalue);
                          else
                              console.log(" member err "+ err);
                          
                    ); 
                    break;
                case '/eventtags':
                    var str = '"eventid" :"2","associatedtags":["2","3"]';
                    //response.render('index');
                    //this method is good becz below code , calling same as 4 both socket & http req 
                    event.eventtags(str,function(err,returnedvalue)
                        
                          if(returnedvalue)
                           console.log(" post result "+returnedvalue);
                          else
                              console.log(" posting err "+ err);
                          
                    ); 
                    break;
                case '/post':
                    var str = '"eventid" :"2","selfid" :"2","title" :"feeedback to event","content" :"bla bla bla","lattitude" :"","longitude" :"","createddatetime" :"","posttype" :"idea","isapporved" :"no","isanonymous" :"no"';
                    //response.render('index');
                    //this method is good becz below code , calling same as 4 both socket & http req 
                    event.post(str,function(err,returnedvalue)
                        
                          if(returnedvalue)
                           console.log(" post result "+returnedvalue);
                          else
                              console.log(" posting err "+ err);
                          
                    ); 
                    break;
                default:
                    response.writeHead(404);
                    response.write("opps this doesn't exist - 404");
                    break;
            
            //just remove this line,& it worked, becz 2 response for a single request
            ***response.end();***


            );
;

【讨论】:

以上是关于在nodejs中发送标头后无法设置标头的主要内容,如果未能解决你的问题,请参考以下文章

发送后无法设置标头 - 通过 NodeJs 发布新用户

UnhandledPromiseRejectionWarning:错误:发送后无法设置标头[重复]

为啥我在 Nodejs 中收到“无法在将标头发送到客户端后设置标头”错误?

将标头发送到客户端后无法设置标头-Nodejs + AWS-S3 getObject

错误:在我初始化会话后发送标头后无法设置标头

发送标头后设置标头时出错 - Node.js