0
votes

how to send file in nodejs, i am creating one page app, so i just want abcd.html page to be delivered on request for first time, here is my code to that

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

response to the page

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

                    break;

it always gives Can't set headers after they are sent, here is the console output

Error: Forbidden at SendStream.error (/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/node_modules/send/lib/send.js:145:16) at SendStream.pipe (/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/node_modules/send/lib/send.js:307:39) at 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 at callbacks (/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/lib/router/index.js:161:37) at param (/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/lib/router/index.js:135:11) at pass (/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/lib/router/index.js:142:5) at Router._dispatch (/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/lib/router/index.js:170:5) at Object.router (/home/pitu/CODING/NODE-PROJECTS/chichat/node_modules/express/lib/router/index.js:33:10) at next (/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.'); ^ Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:331:11) at 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 at fs.js:292:14 at Object.oncomplete (fs.js:93:15)

refrence screenshot screenshot what to do

1
are you sure you don't run into problems due to the .. used in your response.sendfile("../public/abcd.html"); ? more info: stackoverflow.com/questions/14594121/…RemyNL

1 Answers

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


            });
};