Node 创建 Web 服务器

以下是演示一个最基本的 HTTP 服务器架构(使用 8080 端口),创建 server.js 文件,代码如下所示:

实例:

var http = require('http');

var fs = require('fs');

var url = require('url');

// 创建服务器

http.createServer( function (request, response) {

// 解析请求,包括文件名

var pathname = url.parse(request.url).pathname;

// 输出请求的文件名

console.log("Request for " + pathname + " received.");

// 从文件系统中读取请求的文件内容

fs.readFile(pathname.substr(1), function (err, data) {

if (err) {

console.log(err);

// HTTP 状态码: 404 : NOT FOUND

// Content Type: text/plain

response.writeHead(404, {'Content-Type': 'text/html'});

}else{

// HTTP 状态码: 200 : OK

// Content Type: text/plain

response.writeHead(200, {'Content-Type': 'text/html'});

// 响应文件内容

response.write(data.toString());

}

// 发送响应数据

response.end();

});

}).listen(8080);

// 控制台会输出以下信息

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

接下来我们在该目录下创建一个 index.html 文件,代码如下:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>菜鸟教程(runoob.com)</title>

</head>

<body>

<h1>我的第一个标题</h1>

<p>我的第一个段落。</p>

</body>

</html>

执行 server.js 文件:

$ node server.js
Server running at http://127.0.0.1:8080/

接着我们在浏览器中打开地址:http://127.0.0.1:8080/index.html,显示如下图所示:

执行 server.js 的控制台输出信息如下:

Server running at http://127.0.0.1:8080/
Request for /index.html received.     #  客户端请求信息

猜你喜欢

转载自blog.csdn.net/weixin_42413684/article/details/82691210