http模块

1.引入http模块

const http = require('http')

2.创建node服务器

在创建node服务器的时候需要使用http模块中的http.creatServer()方法来进行创建,并且使用listen方法来绑定一个闲置的端口,通过request和response参数来进行接收和响应数据。

//引入http模块
const http = require('http')
//创建http服务
http.createServer((request,reponse)=>{
    //发送http的请求头  第一个参数为http的状态值   第二个是指定文件类型和字符集
    response.writeHead(200,{'Content-type':'text/html;charset=UTF-8'})
    //发送一个服务的响应信息 'hello world'
    res.write('hello world')
    //一次请求可以写多个res.write进行返回数据,但是必须要进行res.end()进行结束相应,否则服务器一直会保持响应状态不会进行发送数据
    res.end()
    //如果处理的数据比较少也可以直接使用res.end()进行发送数据
    res.end('hello world')
}).listen(8000)

3.运行程序

1.运行程序的时候 同时按下windows+r键
2.输入cmd,进入黑窗口
3.切换到文件所对应的目录
4.启动服务
$ node +文件名

4.在浏览器输入地址+端口号进入查看,例如

1. 127.0.0.1:8000
2. locahost:8000
posted @ 2019-07-30 23:23  你是远方  阅读(634)  评论(0编辑  收藏  举报