在这之前,我对
node.js
是只闻其名,未见其身啊,学习了ajax
,老师说用node.js
搭建一个自己的服务器,老师也讲了实现原理,但还是一知半解,怎么办?只好去看看node.js教程了
好了,话不多说,先了解一个node.js应用由哪几部分组成
-
引入 required 模块:我们可以使用
require
指令来载入Node.js
模块。 -
创建服务器:服务器可以监听客户端的请求,类似于
Apache 、Nginx
等HTTP
服务器。 -
接收请求与响应请求 服务器很容易创建,客户端可以使用浏览器或终端发送
HTTP
请求,服务器接收请求后返回响应数据。
步骤一:引入 required 模块
我们使用 require
指令来载入http 模块
,并将实例化的 HTTP
赋值给变量http
var http = requier("http")
步骤二、创建服务器
使用http.createServer()
方法创建服务器,并使用 listen 方法绑定 8888 端口。 函数通过request, response
参数来接收和响应数据。
http.createServer(function (request, response) {
// 发送 HTTP 头部
// HTTP 状态值: 200 : OK
// 内容类型: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// 发送响应数据 "Hello World"
response.end('Hello World\n');
}).listen(8080);
把代码总结起来就是
var http = require('http')
var server = http.createServer(function(request, response){
//.setheader设置响应头 text/plain当成字符串去渲染
response.setHeader("Content-Type","text/plain; charset=utf-8")
response.setHeader('Content-Type','text/html')
//状态码,以及状态码解释
response.writeHead(202, 'haha')
response.write('<html><head><meta charset="utf-8" /></head>')
response.write('<body>')
response.write('<h1>你好</h1>')
response.write('</body>')
response.end()
})
console.log('open http://localhost:8080')
server.listen(8080)
设置响应头
状态码
node执行一下
命令执行
服务器监听8080端口
上面我们了解了node.js怎么使用,下面我们来看看真正写一个静态服务器怎么写?
创建server.js
是如何把我们写的东西展现在服务器上的?
先来了解几个模块
-
Path
模块
Node.js path
模块提供了一些用于处理文件路径的小工具,我们可以通过以下方式引入该模块,有一些方法和属性可以查看文档
var path = require("path")
path.join([path1][, path2][, ...])
用于连接路径。该方法的主要用途在于,会正确使用当前系统的路径分隔符,Unix系统是"/"
,Windows系统是"\"
。
-
Node.js
文件系统
Node.js
提供一组类似UNIX(POSIX)
标准的文件操作API
。Node
导入文件系统模块(fs)
语法如下所示:
var fs = require("fs")
Node.js 文件系统(fs 模块)
模块中的方法均有异步和同步版本,例如读取文件内容的函数有异步的fs.readFile()
和同步的fs.readFileSync()
。
我们看一下静态服务器的原理
- 当用户访问一个地址为
localhost:8080/index.html
,我们怎么样才能让用户看到我们的文件呢? - 我们可以通过函数参数
request
得到这个url
- 得到
url
以后,我们只要在本地找到对应的文件就可以了
过程
静态服务
var http = require('http')
var path = require('path') //处理路径url
var fs = require('fs')
var url = require('url')
//staticRoot静态路径
function staticRoot(staticPath, req, res){
//解析url路径,包括文件名
var pathObj = url.parse(req.url, true)
//默认读index.html
if(pathObj.pathname === '/'){
pathObj.pathname += 'index.html'
}
//请求文件的具体路径
var filePath = path.join(staticPath, pathObj.pathname)
//异步读文件 fs.readFile
//binary 二进制读文件
fs.readFile(filePath, 'binary', function(err, fileContent){
//判断是否读到
if(err){
console.log('404')
res.writeHead(404, 'not found')
res.end('<h1>404 Not Found</h1>')
}else{
console.log('ok')
res.write(fileContent, 'binary')
res.end()
}
})
}
//创建服务器
var server = http.createServer(function(req, res){
staticRoot(path.resolve(__dirname, 'static'), req, res)
})
server.listen(8080)
console.log('visit http://localhost:8080' )
//一个最基本的 HTTP 服务器架构(使用8081端口),创建 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(8081);
// 控制台会输出以下信息
console.log('Server running at http://127.0.0.1:8081/');
上面只是实现了一个简单的静态服务器,只能定位文件夹,我想mock数据,和前端交互怎么弄?
- 看一个简单的例子,请求到达
8080端口
的服务器,我处理对应的路由,域名后面的就是路由
url.parse(string).query
|
url.parse(string).pathname |
| |
| |
------ -------------------
http://localhost:8888/start?foo=bar&hello=world
--- -----
| |
| |
querystring.parse(queryString)["foo"] |
|
querystring.parse(queryString)["hello"]
var http = require('http')
var fs = require('fs')
http.createServer(function(req, res){
//如果解析的路由是/getWeather,To-do
switch (req.url) {
//相当于ajax mock数据
case '/getWeather':
res.end(JSON.stringify({a:1, b:2}))
break;
case '/user/123':
res.end( fs.readFileSync(__dirname + '/static/user' ))
break;
default:
//都没有匹配,是一个静态文件
res.end( fs.readFileSync(__dirname + '/static' + req.url) )
}
}).listen(8080)
第一次短时间接触node.js,对后台知识,以及一些模块什么的理解不太清楚,所以还是有点不足,和面再对这个服务器补充一下