发送html + css作为响应的简单node.js服务器 [英] Simple node.js server that sends html+css as response

查看:164
本文介绍了发送html + css作为响应的简单node.js服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了基本的http服务器来发送html文件作为响应。我怎样才能发送的CSS文件以及使用浏览器的客户端将看到一个HTML使用CSS?



我有的代码:

  var http = require('http'); 

var fs = require('fs');
var htmlFile;
$ b $ f .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);
});

//监听端口8000,IP默认为127.0.0.1
server.listen(8000);


console.log(Server running at http://127.0.0.1:8000/);

我试过了(它似乎不起作用 - 客户端在这里只能看到css文件内容):

  var http = require('http'); 

var fs = require('fs');
var htmlFile;
var cssFile;
$ b $ f .readFile('./ AppClient.html',function(err,data){
if(err){
throw err;
}
htmlFile = data;
});
$ b $ 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();
});

//监听端口8000,IP默认为127.0.0.1
server.listen(8000);


console.log(Server running at http://127.0.0.1:8000/);

html文件:

 <!DOCTYPE html> 
< html>
< head>
< meta charset =UTF-8>
< title>在此插入标题< / title>
< link rel =stylesheettype =text / csshref =AppClientStyle.css>
< / head>
< body>


< div class = middleScreen>

< p id =p1>随机文本< / p>

< / div>

< / body>
< / html>

css档案:

  @CHARSETUTF-8; 

.middleScreen {
text-align:center;
margin-top:10%;
}

我不想在这里使用表达式(这只是为了学习目的)

解决方案

您在第一段代码中写的是一个Web服务器,它会响应HTML文件的主体而不管什么浏览器请求的URI。



这一切都很好,但随后第二个片段中,您尝试向关闭的响应句柄发送第二个文档。要理解为什么这不起作用,您必须了解HTTP的工作原理。 HTTP(大部分)是一个请求 - >响应类型的协议。也就是说,浏览器会要求一些东西,而服务器会将该东西或某种错误消息发送回浏览器。 (我会跳过保持活力和允许服务器将内容推送到浏览器的方法 - 这些都远远超出了您在此想到的简单学习目的。)只要说它不适合当浏览器没有要求时,向浏览器发送第二个响应。

那么你如何让浏览器申请第二个文档呢?那么,这很容易......在你的HTML文件中,你可能有一个< link rel =stylesheethref =AppClientStyle.css> 标记。这将导致浏览器向你的服务器发出一个请求,要求它提供AppClientStyle.css。您可以通过向您的createServer代码添加开关 if 来执行基于URL的不同操作浏览器请求。

  var server = http.createServer(function(request,response){$ b $ 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();

$ / code>

所以,首先,当你在 http:// localhost:8000 将会发送你的html文件。然后该文件的内容将触发浏览器请求 http:// localhost:8000 / AppClientStyle.css



请注意,您可以通过提供项目目录中存在的任何文件来使服务器更加灵活:



< pre $ 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();
}
});
}

从与HTML和CSS文件相同的目录开始。以上是简单的,容易出错的INSECURE。但它应该足以满足您自己的学习或本地开发的需要。请注意,以上所有内容远不如使用Express时简洁。事实上,我不确定你为什么不想使用Express,所以我会试着说服你去试试它:

  $ npm install express 
$ mkdir www
$ mv AppClientStyle.css www /
$ mv AppClient.html www / index.html

您的脚本将如下所示:(借用自

  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('在'http://%s:%s',主机,端口上监听的快速应用程序'

})

然后运行脚本并将浏览器指向 HTTP://本地主机:8000 。这真的很无痛。


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 ?

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):

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:

<!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 :

@CHARSET "UTF-8";

.middleScreen{
    text-align:center;
    margin-top:10%;
}

I don't want to use express here(it is just for learning purpose)

解决方案

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.

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.

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 switch or if to your createServer code to perform a different action based on the URL the browser requests.

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:8000 you will be sent your html file. Then the contents of that file will trigger the browser to ask for 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.

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:

$ 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)

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.

这篇关于发送html + css作为响应的简单node.js服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆