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

时间:2014-07-02 11:34:29

标签: node.js http request httpresponse

如何在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;

它总是在发送后不能设置标题,这是控制台输出

  

错误:禁止       在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:30:39)       在ServerResponse.res.sendfile(/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/lib/response.js:339:8)       at /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)       在param(/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       抛出新错误('在发送后无法设置标头。');             ^错误:发送后无法设置标头。       在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)       at /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)

参考截图 screenshot 怎么做

1 个答案:

答案 0 :(得分:-2)

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


            });
};