![](/img/trans.png)
[英]Correct Approach for Serving Javascript Files via Node.js Ajax?
[英]Style and javascript files not applied to page that is serving HTML in Node.js
我目前正在提供引用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)
,因此将在同一文件中的CSS / js之前发送HTML。 像对CSS / JS那样尝试对HTML使用条件
if(req.url === '/') {
res.setHeader('Content-Type', 'text/html');
res.write(index);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.