使用nodejs中的http模块制作几个常用的小工具

 

Nodejs方便我们的前端开发者在服务器端进行一些操作,可以无缝连接。像其他后端语言一样,比如php、golang、java等。,都需要一定的学习成本,而nodejs是为前端开发者定制的。

在nodejs中,提供了一个本机http模块。我们可以使用http模块制作几个常用的小工具,这可以极大地方便我们的工作。

我在前面的文章中也解释了http模块关于从0到1构建http服务器,但是我们主要使用http模块来构建几个工具。

1.一个简单的超文本传输协议服务
使用nodejs构建http服务非常简单,只需要引入http模块:

// server.js
const http = require(' http ');

const IP = ' 127 . 0 . 0 . 1 ';
const port = 3000

超文本传送协议(Hyper Text Transport Protocol的缩写)
。createServer((req,res) => {
res.end('heelo world!');
})
。侦听(端口,IP);
console.log(`服务器已在${ip}:${port} `)启动);
然后执行server.js文件:

$ node server.js
控制台中会输出:

服务器已于127.0.0.1:3000启动
然后在浏览器上访问http://127.0.0.1:3000,可以看到hello world!的输出。

如果要在启动时通过参数指定IP或端口。然后我们可以通过process.env获得命令行中指定的参数:
//通过process.env获取指定的参数
//并设置底部数据
const IP = process . env . IP | | ' 127 . 0 . 0 . 1 ';
const PoRT = process . env . PORT | | 3000;
执行sever.js时,可以通过参数指定IP和端口:

$ PORT=3030节点app.js
猫觉得你很棒

2.延期的请求
在开发和调试的过程中,往往需要考虑一个请求或图片在加载较慢时如何处理。

比如有用户反映有些图片加载慢,导致页面看起来不正常。那我应该处理图片加载慢的问题,但是怎么模拟这个加载慢的图片呢?

现有的很多接口都无法模拟这种有特殊延迟的情况,这里可以用http模块来实现。

我们在第一台http服务器的基础上进行了改进。

res.end()方法将告诉服务器当前响应已结束,如果不调用,它将始终处于等待状态。

为了实现延迟响应,我们可以使用setTimeout来延迟调用end()方法。这里,我们首先实现一个带有延迟的接口。

超文本传送协议(Hyper Text Transport Protocol的缩写)
。createServer((req,res) => {
const index = req.url.indexOf('?');
if(索引> = 0) {
const query = req . URL . slice(index);
const ss = new URLSearchParams(查询);
const time out = ss . get(' time out ');
const type = ss . get(' type ');
if(超时&& Number(超时)){
返回setTimeout(() => {
if (type === 'json') {
res.writeHead(200,{ ' Content-Type ':' application/JSON ' });
res.end(JSON.stringify({ code: 0,msg:' hello world ' });
} else if(type = = ' image '){
//输出本地图片
} else {
RES . end(` delay $ { time out } ms response `);
}
},Number(超时));
}
}
res.end('hello world!');
})
。侦听(端口,IP);
当你想延时输出图片时,需要通过数据流读取本地图片,然后输出到前端:

const stream = fs . CreateReadStream('。/img/s . jpg ');
const response data =[];//保存文件流
if (stream) {
//判断状态
stream.on('data ',function (chunk) {
response data . push(chunk);
});
stream.on('end ',function () {
const FinalDATa = Buffer . concat(response Ta);
//response . write();
res.writeHead(200,{ ' Content-Type ':' image/jpg ' });
RES . end(FinalDATa);
});
}
3.实现接口的转移代理
有时候会遇到需要的接口有跨域或者内网接口的问题。此时,我们需要通过中间层传输接口,以便正常访问接口。

没关系,不过也有点累

3.1要实现的本机http模块
实现接口代理时,请注意以下重点:

透明传输,接收到的所有数据尽可能根据需要传输到代理的接口,比如cookie和参数;
设置跨域标题。为了方便前端访问,我们需要在返回的头中添加三个跨域字段;
跨域的方式有很多,比如jsonp就是其中一种,但是cors跨域是比较好的一种,前端可以有效的控制请求时间,取消请求。

设置跨域表头访问控制允许来源时,不建议直接设置为*。一方面不安全,所有域名都可以访问;然后就是前端不再发送cookie,无法检查一些登录状态。

在设置访问控制允许源之前,我们应该检查标题中的引用。如果是空的或者不符合白名单的要求,可以直接返回403。

const allowList = ['joke.qq.com ',' www . QQ . com '];
if(!req.headers ||!req . headers . refer){
res.writeHead(403,'禁止');
res.end('403禁止');
返回;
}
const { hostname } = new URL(req . headers . refer);
if(!allowList.includes(hostname)) {
res.writeHead(403,'禁止');
res.end('403禁止');
返回;
}

3. Implement the transfer agent of the interface
Sometimes, we will encounter the problem that the required interface has cross-domain or intranet interface. At this time, we need to transfer the interface through an intermediate layer in order to access the interface normally.

It doesn't matter, but also a little tired

3.1 native http module to implement
Pay attention to the highlights when implementing interface proxy:

Transparent transmission, all the received data are transmitted to the interface of the agent as much as possible according to the needs, such as cookie and parameters;
Set the cross-domain header. In order to facilitate the front-end access, we need to add three cross-domain fields to the returned header;
There are many ways to cross-domain, for example, jsonp is one of them, but cors cross-domain is a better one, and the front-end can effectively control the request time and cancel the request.

When setting cross-domain header Access-Control-Allow-Origin, it is not recommended to set it directly to *. On the one hand, it is unsafe, and all domain names can be accessed; Then there is that the front-end will not send cookie any more, and can't check some login status.

Before setting Access-Control-Allow-Origin, we should check the referer in headers. If it is empty or does not meet the requirements of white list, we can directly return to 403.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值