Node.js封装自己的请求库

161 阅读1分钟

人家Node.js明明有http库,不需要使用什么axios!主要是为了轻量级!!!
HTTPS的话,后续更新!

引入

const http = require('http')

GET请求

function request(options) {
	return new Promise(resolve => {
		let contents,req,reqData;
		Toptions = options

		// 发送请求
		req = http.request(Toptions, res => {
			res.on('data',data => { reqData+=data });
		});
		// 超时挂断
		req.setTimeout(5000,function () {
			req.destroy();
		});
		req.on('end', () => {
			resolve(reqData);
		});
		req.on('error', (e) => {
			resolve({
				code : -1,
				message : e.message
			});
		});
		//必须调用end()
		req.end();
	});
}
// 使用
request({
	host : 'localhost',
	port : 80,
	path : '/',
	// 请求类型
	method:'GET',
	// 头部
	headers : {
		'Content-Type' : 'application/json'
	},
}).then(res => {
	// res是Buffer 可以.toString()获取字符串类型
	console.log(res.toString())
})

POST 请求

function request(options) {
	return new Promise(resolve => {
		let contents,req,reqData;
		Toptions = options
		// 发送请求
		req = http.request(Toptions, res => {
			res.on('data',data => { reqData+=data; });
		});
		// 发送数据
		req.write(contents);
		// 超时挂断
		req.setTimeout(5000,function () {
			req.destroy();
		});
		req.on('end', () => {
			resolve(reqData);
		});
		req.on('error', (e) => {
			resolve({
				code : -1,
				message : e.message
			});
		});
		//必须调用end()
		req.end();
	});
}
// 使用
let data = 'user=123' // 你可以发送json数据 JSON.stringify
request({
	host : 'localhost',
	port : 80,
	path : '/login',
	// 请求类型
	method:'POST',
	data,
	// 头部
	headers : {
		'Content-Type' : 'application/json',
		'Content-Length' : data.length
	},
}).then(res => {
	// res是Buffer 可以.toString()获取字符串类型
	console.log(res.toString())
})