样式和 javascript 文件不适用于在 Node.js 中提供 HTML 的页面 [英] Style and javascript files not applied to page that is serving HTML in Node.js
问题描述
我目前正在为引用 style.css 和 index.js 的 HTML 页面提供服务,但是,这些文件并未应用于 HTML 页面,即使我明确声明在req"请求时包含它们?
I am currently serving my HTML page which references style.css and index.js, however, these files are not being applied to the HTML page even though I explicitly stated to include them if they are requested by 'req'?
我的 HTML(显示包含内容):
My HTML (to show inclusions):
<!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 代码:
My server.js code:
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);
}
推荐答案
看起来您的想法是正确的,但在服务器代码中需要注意一些事项.
Looks like you have the right idea but there are a couple things to note in the server code.
设置 Content Type
标头告诉 Web 浏览器如何解释它接收的文件.您的服务器代码始终将其设置为text/html",其中对于 css 应将其设置为text/css",对于 js 文件应将其设置为text/javascript".
Setting the Content Type
header tells the web browser how to interpret the file it is receiving. Your server code always sets it to 'text/html' where it should be set to 'text/css' for css, and 'text/javascript' for your js files.
res.write
会将文件内容附加到响应中.由于 res.write(index)
正在对每个请求执行,因此您的 HTML 将在同一文件中的 css/js 之前发送.尝试对 HTML 使用条件,就像对 CSS/JS 一样
res.write
will append the file contents to the response. Since res.write(index)
is being executed on every request, your HTML is being sent before the css/js within the same file. Try using a conditional for HTML like you are doing for CSS/JS like
if(req.url === '/') {
res.setHeader('Content-Type', 'text/html');
res.write(index);
}
这篇关于样式和 javascript 文件不适用于在 Node.js 中提供 HTML 的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!