2016-10-24 38 views
0

我有一個簡單的html頁面,並且正在嘗試通過節點爲它服務。'content-type':'text/html'直到服務器死亡才被接受

當我將內容類型設置爲文本/純文本時,加載html文件的純文本。但是,當我將其更改爲「content-type」:「text/html」時,瀏覽器選項卡會連續加載而不更新。一旦我殺死節點應用程序,瀏覽器就會顯示該頁面,就好像它完全加載一樣。

Server代碼:

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(); 

    } 

指數:

<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> 
+0

[Express.js接近響應(HTTP的可能重複: //www.stackoverflow.com/questions/13554319/express-js-close-response) – NineBerry

+0

使用連接頭的另一種方法是正確添加內容長度頭。 – NineBerry

+0

@NineBerry,謝謝你的迴應。我已經將連接關鍵字/值添加到writeHead,並嘗試添加內容長度,但我仍然遇到同樣的問題。 –

回答

2

你需要這樣,當文件結束你的瀏覽器知道添加Content-Length頭。你可以通過修改你的代碼,像這樣:

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

Node.js的文檔有些提到了這一點,在res.writeHead的底部:https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers

+0

@PaulBDG,謝謝。我添加了內容長度字段,但仍然有相同的問題。任何想法爲什麼? –

+0

你使用什麼瀏覽器? – PaulBGD

+0

Chrome版本53 –

相關問題