Javascript 发送 html+css 作为响应的简单 node.js 服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28822034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple node.js server that sends html+css as response
提问by kiluk876
I've created basic http server that sends html file as response. How can I send css file as well so client using browser will see a html using css ?
我已经创建了发送 html 文件作为响应的基本 http 服务器。如何发送 css 文件,以便使用浏览器的客户端会看到使用 css 的 html?
The code I have:
我有的代码:
var http = require('http');
var fs = require('fs');
var htmlFile;
fs.readFile('./AppClient.html', function(err, data) {
if (err){
throw err;
}
htmlFile = data;
});
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.end(htmlFile);
});
//Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
What I have tried(it seems it does not work - client sees only css file content here):
我尝试过的(似乎不起作用 - 客户端在这里只能看到 css 文件内容):
var http = require('http');
var fs = require('fs');
var htmlFile;
var cssFile;
fs.readFile('./AppClient.html', function(err, data) {
if (err){
throw err;
}
htmlFile = data;
});
fs.readFile('./AppClientStyle.css', function(err, data) {
if (err){
throw err;
}
cssFile = data;
});
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/css"});
response.write(cssFile);
response.end();
response.writeHead(200, {"Content-Type": "text/html"});
response.write(htmlFile);
response.end();
});
//Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
html file:
html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="AppClientStyle.css">
</head>
<body>
<div class=middleScreen>
<p id="p1">Random text</p>
</div>
</body>
</html>
css file :
css文件:
@CHARSET "UTF-8";
.middleScreen{
text-align:center;
margin-top:10%;
}
I don't want to use express here(it is just for learning purpose)
我不想在这里使用express(仅用于学习目的)
回答by Andy Zarzycki
What you have written in your first snippet is a web server that responds with the body of your HTML file regardless of what URI the browser requests.
您在第一个代码段中编写的是一个 Web 服务器,无论浏览器请求什么 URI,它都会响应您的 HTML 文件的正文。
That's all nice and well, but then with the second snippet, you're trying to send a second document to a closed response handle. To understand why this doesn't work, you have to understand how HTTP works. HTTP is (for the most part) a request->response type protocol. That is, the browser asks for something and the server sends that thing, or an error message of some sort, back to the browser. (I'll skip over keep-alive and methods that allow the server to push content to the browser--those are all far beyond the simple learning purpose you seem to have in mind here.) Suffice it to say that it is inappropriate to send a second response to the browser when it hasn't asked for it.
这一切都很好,但是对于第二个片段,您尝试将第二个文档发送到关闭的响应句柄。要了解为什么这不起作用,您必须了解 HTTP 的工作原理。HTTP 是(在大多数情况下)请求-> 响应类型的协议。也就是说,浏览器请求某些东西,服务器将那个东西或某种错误消息发送回浏览器。(我将跳过 keep-alive 和允许服务器将内容推送到浏览器的方法——这些都远远超出了您在这里似乎想到的简单学习目的。)我只想说这是不合适的当浏览器没有要求它时,向浏览器发送第二个响应。
So how do you get the browser to ask for a second document? Well, that's easy enough... in your HTML file you probably have a <link rel="stylesheet" href="AppClientStyle.css">tag. This will cause the browser to make a request to your server asking it for AppClientStyle.css. You can handle this by adding a switchor ifto your createServer code to perform a different action based on the URL the browser requests.
那么如何让浏览器请求第二个文档呢?嗯,这很简单……在您的 HTML 文件中,您可能有一个<link rel="stylesheet" href="AppClientStyle.css">标签。这将导致浏览器向您的服务器发出请求,要求它提供 AppClientStyle.css。您可以通过向createServer 代码添加switch或if来处理此问题,以根据浏览器请求的 URL 执行不同的操作。
var server = http.createServer(function (request, response) {
switch (request.url) {
case "/AppClientStyle.css" :
response.writeHead(200, {"Content-Type": "text/css"});
response.write(cssFile);
break;
default :
response.writeHead(200, {"Content-Type": "text/html"});
response.write(htmlFile);
});
response.end();
}
So, first, when you access your server at http://localhost:8000you will be sent your html file. Then the contents of that file will trigger the browser to ask for http://localhost:8000/AppClientStyle.css
因此,首先,当您通过http://localhost:8000访问您的服务器时,您将收到您的 html 文件。然后该文件的内容将触发浏览器请求http://localhost:8000/AppClientStyle.css
Note that you can make your server far more flexible by serving any file that exists in your project directory:
请注意,您可以通过提供项目目录中存在的任何文件来使您的服务器更加灵活:
var server = http.createServer(function (request, response) {
fs.readFile('./' + request.url, function(err, data) {
if (!err) {
var dotoffset = request.url.lastIndexOf('.');
var mimetype = dotoffset == -1
? 'text/plain'
: {
'.html' : 'text/html',
'.ico' : 'image/x-icon',
'.jpg' : 'image/jpeg',
'.png' : 'image/png',
'.gif' : 'image/gif',
'.css' : 'text/css',
'.js' : 'text/javascript'
}[ request.url.substr(dotoffset) ];
response.setHeader('Content-type' , mimetype);
response.end(data);
console.log( request.url, mimetype );
} else {
console.log ('file not found: ' + request.url);
response.writeHead(404, "Not Found");
response.end();
}
});
})
Start this in the same directory as your HTML and CSS files. The above is simplistic, error-prone and INSECURE. But it should be sufficient for your own learning or local development purposes.
在与 HTML 和 CSS 文件相同的目录中启动它。以上是简单的,容易出错和不安全的。但是对于您自己的学习或本地发展目的来说应该足够了。
Keep in mind that all the above is far less succinct than just using Express. In fact, I'm not sure why you wouldn't want to use Express, so I'm going to try to convince you to try it:
请记住,以上所有内容远不如仅使用 Express 简洁。事实上,我不确定你为什么不想使用 Express,所以我将尝试说服你尝试它:
$ npm install express
$ mkdir www
$ mv AppClientStyle.css www/
$ mv AppClient.html www/index.html
Your script will look like: (Borrowed from Express Hello World)
您的脚本将如下所示:(从Express Hello World借来)
var express = require('express')
var app = express()
app.use(express.static('www'));
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log('Express app listening at http://%s:%s', host, port)
})
Then run your script and point your browser to http://localhost:8000. It really is that painless.
然后运行您的脚本并将浏览器指向http://localhost:8000。真的是那么无痛。
回答by Steffi A.
Integrate the CSS right into your AppClient.htmlfile. There are different ways to do so:
将 CSS 直接集成到您的AppClient.html文件中。有不同的方法可以做到这一点:
External CSS file
外部 CSS 文件
Create a styles.cssfile (or any other file name) in the same directory as your html file. Then add
styles.css在与 html 文件相同的目录中创建一个文件(或任何其他文件名)。然后加
<link rel="stylesheet" type="text/css" href="styles.css">
to your <head>section of your HTML document.
到您<head>的 HTML 文档部分。
OR
或者
Right in your HTML file
就在您的 HTML 文件中
Add a
添加一个
<style>
YOUR STYLES RIGHT HERE
</style>
to your <head>section of your HTML document.
到您<head>的 HTML 文档部分。

