Node.js http模块问题-当我读取我的文件并在本地主机中打开时,我给读取的文件没有执行,而是变量名



JavaScript 如您所见,我尝试读取(1.html(,但在localhost中得到了变量(fileContent(作为结果

const http = require('http')
const fs = require("fs")
const fileContent = fs.readFileSync('1.html')
const server = http.createServer((req, res)=>{
res.writeHead(200, {'content-type':'text/html'});
res.end('1.html')
})
server.listen(80, '127.0.0.1',()=>{
console.log(`Server running at http://${ "127.0.0.1"}:${80}/`);
})

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>

您将内容类型设置为text/plain,并在res.end((中写入字符串。

Set('Content-type':'text/html'(和res.end(fileContent(,其中fileContent是您为读取html文件而设置的变量。

const http = require("http");
const fs = require("fs");
const fileContent = fs.readFileSync("1.html");
const server = http.createServer((req, res) => {
res.writeHead(200, { "content-type": "text/html" });
res.end(fileContent);
});
server.listen(80, "127.0.0.1", () => {
console.log(`Server running at http://${"127.0.0.1"}:${80}/`);
});

相关内容

  • 没有找到相关文章

最新更新