-1

This is my code:-

const express = require("express");

const app = express();

app.get("/", function (req,res) {
   res.send("<h1>Hello World</h1>");
   res.send(__dirname + '\\index.html');
});
    
app.listen(3000, function () {
   console.log("Server is running on port 3000");
   
});

enter image description here

I was expecting to run code properly and the file properly send to given location

seenukarthi
  • 8,241
  • 10
  • 47
  • 68

1 Answers1

0

Try removing the first res.send line

res.send("<h1>Hello World</h1>");

because the .send method sends an argument value, already held in memory, back to the browser, and you can't reply (send a response) to the same request twice. The error is generated for the second send and is worded "Cannot set headers after they are sent to the client".

Then change the second send to

res.sendFile(__dirname + '\\index.html');

to have Express read the index file and send it to the client using the sendFile method.

I recommend looking up and reading Express documentation when in doubt - take the link, select "response" in the left hand column and scroll down for res.send and res.sendFile entries.

traktor
  • 17,588
  • 4
  • 32
  • 53