最近,接手到一个项目,在测试阶段需要频繁的打包 -> 上传 -> 新建 -> … -> … 于是想着能不能将这些重复无脑的工作使用代码简化了,于是便有了文章标题名字的问题.
要想完成这个工作首先要有个可以发起的http请求的工具,这里我是使用了http(s).request这个方法,他会为我们创建一个http.ClientRequest类的对象 我们基于这个对象可以完成一次http请求的发送和响应的接收。
eg:
const options = {hostname:'host',port: 443,path:'path',method: 'method',headers:{}}const hcr = http.request(options,(res) => {// 这里接收响应let chunks = Buffer.from([]);res.on('data', chunk => {chunks = Buffer.concat([chunks,chunk])});res.on('end',() =>{const res = JSON.parse(chunks.toString('utf-8'));console.log(res,'就是我们接收到的响应')})})hcr.end('要发送的数据')
基本上一个普通的http post请求在设置好请求头后在end里直接将键值对数据JSON stringify了发送就行,但是在发送文件的时候,有个东西我们必须得知到就是发送文件的数据格式,以chrmome举例,在一个请求头为Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryGe1u5fl4IETGv48y的传输中,数据格式是这样的:
------WebKitFormBoundaryGe1u5fl4IETGv48yContent-Disposition: form-data; name="type"H5------WebKitFormBoundaryGe1u5fl4IETGv48yContent-Disposition: form-data; name="file"; filename="package1.0.161.zip"Content-Type: application/x-zip-compressed这里就是二进制数据了------WebKitFormBoundaryGe1u5fl4IETGv48y--
这个格式就是以boundary作为开始结束和字段之间的间隔,中间有一些请求头和真实数据,并且以换行符(\r\n)分割,请求头所在行的name就是服务端接收这个字段的key,所以我们照着拼好这个格式就可以搞定传输了:
let chunks = Buffer.from([]);let endBuffer = ([Buffer.from(`--${boundaryKey}\r\n`),Buffer.from(`Content-Disposition: form-data; name="type"\r\n`),Buffer.from(`\r\n`),Buffer.from(`H5\r\n`),Buffer.from(`--${boundaryKey}\r\n`),Buffer.from(`Content-Disposition: form-data; name="file"; filename="${'文件名'}\r\n`),Buffer.from(`Content-Type: application/x-zip-compressed\r\n`),Buffer.from(`\r\n`),fs.readFileSync(`你的文件路径`),Buffer.from(`\r\n`),Buffer.from(`--${boundaryKey}--`)])endBuffer.forEach( buf => {chunks = Buffer.concat([chunks,buf])})
拼好这个chunks,配置好options请求头的Content-Type然后使用end方法将其发送就ok了。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号