我目前正在为引用 style.css 和 index.js 的 HTML 页面提供服务,但是,即使我明确声明在“req”请求时包含它们,这些文件也没有应用于 HTML 页面?
我的 HTML(显示包含):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test site</title>
<link rel="stylesheet" href="/style.css" media="screen">
<script src="/index.js" charset="utf-8" defer></script>
.
.
.
我的 server.js 代码:
var PORT = 3000;
var http = require('http');
var fs = require('fs');
var path = require('path');
//cache the files
var index = fs.readFileSync('public/index.html', 'utf8', function read(err, data) {
if (err) {
throw err;
}
});
var style = fs.readFileSync('public/style.css', 'utf8', function read(err, data) {
if (err) {
throw err;
}
});
var indexJS = fs.readFileSync('public/index.js', 'utf8', function read(err, data) {
if (err) {
throw err;
}
});
function requestHandler(req, res){
res.setHeader('Content-Type', 'text/html');
res.statusCode = 200
res.write(index);
if(req.url === '/style.css'){
res.write(style);
}
if(req.url === '/index.js'){
res.write(indexJS);
}
res.end();
}
//use 3000 by default if PORT is not defined
if(!(typeof PORT !== 'undefined') || PORT === null){
http.createServer(requestHandler).listen(PORT);
}
else{
http.createServer(requestHandler).listen(3000);
}
看起来您的想法是正确的,但在服务器代码中有几件事需要注意。
设置Content Type
标题会告诉 Web 浏览器如何解释它正在接收的文件。您的服务器代码始终将其设置为“text/html”,对于 css 应将其设置为“text/css”,对于 js 文件应设置为“text/javascript”。
res.write
将文件内容附加到响应中。由于res.write(index)
在每个请求上都执行,因此您的 HTML 将在同一文件中的 css/js 之前发送。尝试对 HTML 使用条件,就像对 CSS/JS 一样
if(req.url === '/') {
res.setHeader('Content-Type', 'text/html');
res.write(index);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句