gpt4 book ai didi

javascript - “内容类型”: 'text/html' not accepted until server is killed

转载 作者:行者123 更新时间:2023-12-02 14:03:51 26 4
gpt4 key购买 nike

我有一个简单的 html 页面,并尝试通过 Node 提供服务。

当我将内容类型设置为文本/纯文本时,将加载 html 文件的纯文本。但是,当我将其更改为“content-type”:“text/html”时,浏览器选项卡会持续加载而不会更新。一旦我终止 Node 应用程序,浏览器就会显示页面,就好像它已完全加载一样。

服务器代码:

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>

最佳答案

您需要添加 Content-Length header ,以便浏览器知道文件何时结束。您可以通过修改代码来实现这一点,如下所示:

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

关于javascript - “内容类型”: 'text/html' not accepted until server is killed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40209483/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com