Something is missing Something is missing - 1 month ago 13
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) {
homeRoute(req,res)
}).listen(3000);
console.log('test');


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

}


Index:

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

<head>
<meta charset="UTF-8">
<title>Corporate Ipsum</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" integrity="sha384-AysaV+vQoT3kOAXZkl02PThvDr8HYKPZhNT5h/CXfBThSRXQ6jW5DO2ekP5ViFdi" crossorigin="anonymous">
<link rel="stylesheet" href="https://necolas.github.io/normalize.css/5.0.0/normalize.css">
<link rel="stylesheet" href="css/main.css"> </head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="src/app.js"></script>

<body>
<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>

</form>

</div>
</div>



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

Answer

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 
        res.end();
    }

The Node.js documentation somewhat mentions this at the bottom of res.writeHead: https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers

Comments