7

nodejs中如何使用http创建一个服务

 3 years ago
source link: https://segmentfault.com/a/1190000040401105
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

nodejs中如何使用http创建一个服务

发布于 今天 14:35

http模块是nodejs中非常重要的一部分,用于开启一个服务,我们可以用它自定义接口供客户端使用。

开启服务的方式也比较简单,几行代码就可以搞定

const http = require('http')
const server = http.createServer((req, res)=>{
  res.end('hello world')
})
server.listen('8000', ()=> {console.log('8000端口已启动~')})
// 在命令行工具中输入 node [当前的文件名] 即可启动,启动成功后在命令行工具输出:8000端口已启动~

通过 createServer 创建服务时,传入的回调函数里的两个参数分别是request和result即请求和响应,request里有很多和请求相关的参数。
常用的属性是url、method和headers即请求的链接,方法和头部信息,头部信息里又包括了主机名、可接受压缩的形式、请求类型、请求长度等等。
http模块需要根据这些信息进行不同的请求处理,从而给客户端返回相对应的结果。用postman模拟发送post请求,打印的request的三个参数如下图所示。

get请求的参数可以通过url直接获取,并对数据进行处理,而post请求的参数是放在body中的,不能直接通过header获取,需要通过 req.on来监听参数的内容,获取到的数据类型默认是 Buffer,可以通过req.setEncoding设置为需要的数据类型,utf-8、binary等,或者通过Buffer数据toString()方法可以转换成 utf-8的编码形式

const server = http.createServer((req, res)=>{
  console.log('req.url:', req.url)
  req.on('data', data=>{
    console.log('post请求的data: ',data.toString())
  })
  res.end('hello world')
})

http的请求和响应是以数据流的形式传递的,响应可以通过 end方法来写入响应内容并关闭流,默认是相应格式为text类型,如果需要传递其他类型的响应结果,需要通过setHeader或者writeHead来定义Content-Type,Content-Type默认是 text/plain,即文本,更改为 text/html 即下图展示的html渲染方式

const server = http.createServer((req, res)=>{
  res.setHeader("Content-Type", "text/html")
  res.end('<h1>hello node</h1>')
})

image.png

http模块可以开启一个服务,用来处理客户端发送过来的http请求,同时,它也可以发送http请求,get请求和post请求接收响应的相同点在于都需要通过on来监听data,从回调函数中获取响应结果,不同点在于post请求还需要监听请求结束的end方法,当end方法执行时,再关闭此次post请求。

const http = require('http')

// get请求监听data方法
http.get('http://localhost:8000', (res)=>{
  res.on('data', data=>{
    console.log('get请求的响应:', data.toString())
  })
})

// post请求还需监听end方法,以及关闭请求
const req = http.request({
  method: 'post',
  port: 8000,
  hostname: 'localhost'
}, res=>{
  res.on('data', data=>{
    console.log('post请求的响应:',data)
  })

  res.on('end', ()=>{
    console.log('post请求获取到了所有请求结果')
  })
})
req.end()

image.png

http模块的复杂点在于处理请求参数,get请求的参数通过字符串解析url就可以,post请求需要根据上传类型来进行区分,上传的是json数据、urlencoded还是文件,解析的方式都不相同,所以通常会使用框架来简化我们的编码流程, express和koa都极大的简化了逻辑的处理过程。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK