0

JavaScript As you can see, i tried to read (1.html) but i got the variable (fileContent) as the result in localhost.

const http = require('http')
const fs = require("fs")
const fileContent = fs.readFileSync('1.html')

const server = http.createServer((req, res)=>{
    res.writeHead(200, {'content-type':'text/html'});
    res.end('1.html')
})

server.listen(80, '127.0.0.1',()=>{
    console.log(`Server running at http://${ "127.0.0.1"}:${80}/`);
})

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello</h1>
</body>
</html>
JPT3
  • 1
  • 4
  • Does this answer your question? [nodejs send html file to client](https://stackoverflow.com/questions/20345936/nodejs-send-html-file-to-client) – filipe Aug 27 '22 at 06:19

1 Answers1

1

You set content-type as text/plain and wrote string in res.end().

Set ('Content-type': 'text/html') and res.end(fileContent) where fileContent is variable you set for reading html file.

const http = require("http");
const fs = require("fs");
const fileContent = fs.readFileSync("1.html");

const server = http.createServer((req, res) => {
    res.writeHead(200, { "content-type": "text/html" });
    res.end(fileContent);
});

server.listen(80, "127.0.0.1", () => {
    console.log(`Server running at http://${"127.0.0.1"}:${80}/`);
});
Aniket Chauhan
  • 386
  • 2
  • 6