//1、引入http
var http=require('http')
//2、使用http.createServer()方法创建一个web服务,返回一个server实例
var server=http.createServer()
//3、服务器要干嘛:
//提供服务:数据的服务
//发请求
//接收请求
//处理请求
//给个反馈
//注册requesr请求事件
//当客服端请求过来,就会自动触发服务器的request请求事件,然后执行第二个参数:回调处理
//请求事件处理函数,需要接收两个参数:Request,Response
//Request:请求队形:请求对象可以用来获取客服端的一些请求信息,
//Response:响应对象:响应对象可以用来设置服务端给客服端发送响应数据
server.on('request',function (request,response) {
//response对象中write可以用来给客服端发送响应数据,但是最后一定要使用end来结束响应,否则客服端会一直等待
response.write('hello world!!!')
response.end()
/*if (request.url=='/index'||request.url==='/'){
//注意响应内容只能是字符串或者二进制数据,不能是数组或者对象
var data=[
{ name:'apple',price:300},
{ name:'apple',price:300},
{ name:'apple',price:300},
{ name:'apple',price:300}
]
response.end(JSON.stringify(data))//发送响应数据的同时结束响应
} else {
response.end('hello world!!!')
}*/
})
//4、绑定端口号,启动服务器
server.listen(3000,function () {
console.log('服务器启动成功,可以通过http:127.0.0.1:3000来访问')
})
node http创建服务
最新推荐文章于 2024-04-04 09:59:46 发布