我们可以用node构建一个web服务器
在node中专门提供了一个核心模块:http
//1. 加载http核心模块
var http = require('http')
//2. 创建一个Server实例
var server = http.createServer()
//3. 当客户端请求过来,就会自动触发服务器的request请求事件,然后执行第二个参数:回调处理函数
server.on('request', function(){
console.log('收到客户端情求了')
})
//4.绑定端口号,启动服务器
server.listen(3000, function(){
console.log('服务器启动成功,可通过http://127.0.0.1:3000来进行访问')
})
更深一步
可以调用response.write方法写完,再去response.end()
也可以直接用response.end(),如下
//1. 加载http核心模块
var http = require('http')
//2. 创建一个Server实例
var server = http.createServer()
//3. 当客户端请求过来,就会自动触发服务器的request请求事件,然后执行第二个参数:回调处理函数
//request 请求对象,用来获取客户端的一些请求信息,例如请求路径
//response 响应对象,用来给客户端发送响应信息
server.on('request', function(request, response) {
console.log('收到客户端情求了,请求路径是:' + request.url)
// reponse 对象有一个方法: write ,可以用来给客户端发送响应数据
// write 可以使用多次, 但是最后一定要用end来结束响应,否则客户端会一直等待
// request.url获得的是端口号之后的那一部分路径
var url = request.url
if(url === '/') {
response.end('This is index page')
} else if(url === '/profile') {
response.end('This is profile')
} else {
response.end('404 not found')
}
})
//4.绑定端口号,启动服务器
server.listen(3000, function() {
console.log('服务器启动成功,可通过http://127.0.0.1:3000来进行访问')
})
测试1
测试2
测试3
注意:响应数据只能是二进制数据或者字符串,数字,对象都不行
如果我的响应数据是一个对象
var products = [
{
name: '苹果',
price: 40
},
{
name: '梨',
price: 20
},
{
name: '西瓜',
price: 30
},
]
要转为字符串
response.end(JSON.stringify(products))
ps: JSON.prase()方法是将字符串转为对象
中文乱码问题
服务器默认发送的内容是utf-8编码的
但浏览器默认安装当前操作系统的默认编码进行解析,中文操作系统默认是gbk
解决
var url = req.url
if(url == '/plain') {
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('你好')
} else if(url == '/html') {
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.end('<p>hello html<a href="">点我</a></p>')
}
传文件
var http = require('http')
var fs = require('fs')
var server = http.createServer()
server.on('request', function(req,res) {
var url = req.url
if(url == '/') {
fs.readFile('./resource/index.html', function(err, data) {
if(err) {
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('文件读取失败,请稍后重试!')
} else {
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.end(data)
}
})
}
})
server.listen(5000, function() {
console.log('服务器启动成功,可通过http://127.0.0.1:5000来进行访问')
})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Document</title>
</head>
<body>
<h1>首页</h1>
<h2>相逢何必曾相识</h2>
</body>
</html>
运行效果
传图片
改一下Content-Type,而且图片就不需要编码了
res.setHeader('Content-Type', 'image/jpeg')
其它类型的文件的Content-Type