我有一个简单的html页面,我试图通过节点提供它。
当我将内容类型设置为text / plain时,会加载html文件的纯文本。但是,当我将其更改为“content-type”:“text / html”时,浏览器选项卡会持续加载而不进行更新。一旦我杀死节点应用程序,浏览器就会将页面显示为完全加载。
服务器代码:
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 :(得分: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