簡體   English   中英

'content-type':'text / html'不被接受,直到服務器被殺死

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

我有一個簡單的html頁面,正在嘗試通過node提供服務。

當我將內容類型設置為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>

您需要添加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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM