user4046073 user4046073 -4 years ago 163
HTML Question

Node Express sever error : Can't render headers after they are sent to the client

I'm fairly new to this. I created a node-express server that runs locally. And I have a

folder. When I visit that index page, I got an error
Can't render headers after they are sent to the client node server error
. My understanding is that if the url is localhost:8080 plus
, index.html will be rendered? How do I solve this problem? Many thanks!

ps: The odd thing is that when I move index.html out from the "public" folder to the same directory with the node server.js, and change to
app.get('/', function (req, res {fs.readFile('/index.html'..
the index.html seems to work fine.

var fs = require('fs');
var http = require('http');
var https = require('https');
var request = require('request');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var path = require('path');
var express = require('express');
var app = express();
var certificate = fs.readFileSync( 'something.0.0.1.cert' );
var privateKey = fs.readFileSync('something.0.0.1.key');

app.get('/', function (req, res) {
fs.readFile('__dirname + '/public'+ '/html'+/index.html', function(error, content) {
if (error) {
else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
res.send('Hello World');

key: privateKey,
cert: certificate
}, app).listen(8080,'');

Answer Source

You only get one response for every request. Your code shows res.send('Hello World');

change this to res.sendFile("__dirname + '/public/html/' + 'index.html' ")

You can remove the fs.readFile line too.

The reason fs.readFile('/index.html') works when you move to the same file as your server is because that line means to read a file called index.html from the same directory. But you want to send a response to a request, not just read files.

Check out the docs on res.sendFile in express

Try this:

    app.get('/', function (req, res) {
         res.sendFile(__dirname + '/public/html/'+'index.html'); 

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download