我目前正在为引用 style.css 和 index.js 的 HTML 页面提供服务,但是,这些文件没有应用到 HTML 页面,即使我明确声明如果它们被“req”请求则包含它们?
我的 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
header 告诉网络浏览器如何解释它接收的文件。您的服务器代码始终将其设置为“text/html”,对于 css 应设置为“text/css”,对于 js 文件应设置为“text/javascript”。
res.write
会将文件内容附加到响应中。由于 res.write(index)
是在每个请求上执行的,因此您的 HTML 在同一文件中的 css/js 之前发送。尝试像对 CSS/JS 那样对 HTML 使用条件
if(req.url === '/') {
res.setHeader('Content-Type', 'text/html');
res.write(index);
}
关于javascript - 样式和 javascript 文件不适用于在 Node.js 中提供 HTML 的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50429529/