Something is missing Something is missing - 1 year ago 64
Javascript Question

'content-type': 'text/html' not accepted until server is killed

I have a simple html page and am trying to serve it via node.

When I set the content type to text/plain, the plain text of the html file loads. However, when I change it to "content-type" : "text/html" the browser tab continuously loads without update. Once I kill the node app, the browsers shows the page as if it was loaded completely.

Server code:

var http = require('http');
var query = require('querystring');
var fs = require('fs');
http.createServer(function (req, res) {

function homeRoute(req, res) {
if (req.url === '/') {
var html = fs.readFileSync('./Index.html', {encoding: 'utf-8'});
res.writeHead(200, {"Content-Type": "text/html"});



<DOCTYPE html>
<html lang="en">

<meta charset="UTF-8">
<title>Corporate Ipsum</title>
<link rel="stylesheet" href="" integrity="sha384-AysaV+vQoT3kOAXZkl02PThvDr8HYKPZhNT5h/CXfBThSRXQ6jW5DO2ekP5ViFdi" crossorigin="anonymous">
<link rel="stylesheet" href="">
<link rel="stylesheet" href="css/main.css"> </head>
<script src=""></script>
<script src="src/app.js"></script>

<div class="container my-3">
<div class="col-sm-2">
<form method="post" action="/data" class="form-group">
<label for="sentenceCount">Sentences</label>
<input type="number" placeholder="10" name="sentencecount" id="sentenceCount" class="form-control parameters">
<button type="button" id="submit" class="btn btn-primary mt-1">Submit</button>



<div class="container mt-2" style="border:1px solid red">
</body> </html>

Answer Source

You need to add the Content-Length header so that your browser knows when the file ends. You can that by modifying you code like so:

function homeRoute(req, res) {
    if (req.url === '/') {
        var html = fs.readFileSync('./Index.html'); // read this as a buffer
        res.writeHead(200, {"Content-Type": "text/html", "Content-Length": html.length}); // write the buffer's length
        console.log(html.toString('utf8')) // but when logging/writing explicitely say utf8
        res.write(html.toString('utf8')); // you can remove the toString here, but it adds a little readability 

The Node.js documentation somewhat mentions this at the bottom of res.writeHead:

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