NodeJS实现Http请求


PHP中可以通过CUrl请求一个链接,NodeJS中可以通过Http或Https发送请求。

实现如下:

http.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
var httpServer = require("http");
var queryString = require("querystring");

class Http{
constructor(){
this.params = {};
this.isPost = false;
this.req = null;
this.hostname = '';
this.port = 80;
this.urlPath = '';
this.protocol = 'http:';
this.timeout = 10000;
this.headers = {};
}

/**
 * [setParams description]
 * @param {Object} [params] {key:value}
 */
setParams(params){
this.params = queryString.stringify(params);
}

setHostName(hostname){
this.hostname = hostname;
}

setUrlPath(path){
this.urlPath = path;
}

setIsPost(isPost){
this.isPost = isPost;
}

setPort(port){
this.port = port;
}

setProtocol(protocol){
this.protocol = protocol;
}

setTimeout(timeout){
this.timeout = timeout;
}

/**
 * [setHeader description]
 * @param {[Object]} headers [description]
 */
setHeader(headers){
this.headers = headers;
}

sendRequest(){
let options = {
protocol:this.protocol,
hostname:this.hostname,
portthis.port,
paththis.urlPath,
method"GET",
timeout:this.timeout,
headers:this.headers
}
if (this.isPost) {
options.method = "POST";
options.headers['Content-Type'] = "application/x-www-form-urlencoded";
options.path = this.urlPath;
options.headers['Content-Length'] = Buffer.byteLength(this.params);
else {
options.path = this.urlPath + "?" + this.params;
}
return new Promise((resolve, reject)=>{
this._request(options).then((res)=>{
this._getResponse(res).then((chunk)=>{
resolve(chunk.toString());
});
}).catch((msg)=>{
reject(msg);
});
this._requestStatus().then((err)=>{
reject(err);
});
});
}

_getResponse(res){
return new Promise((resolve, reject)=>{
//res.setEncoding('utf8');
res.on("data"(chunk) => {
resolve(chunk);
});
});
}

_requestStatus(){
return new Promise((resolve, reject)=>{
this.req.on('error'function (e) {
     resolve(e);
});
if (this.isPost) {
this.req.write(this.params);
}
this.req.end();
});
}

_request(options){
return new Promise((resolve, reject)=>{
this.req = httpServer.request(options, (res)=>{
if (res) {
resolve(res);
else {
reject("请求失败");
}
});
});
}
}

module.exports = Http;

测试以上类:

request.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var Http = require("http.js");

class Request{
constructor(){
this.http = new Http();
}
getTest(){
this.http.setProtocol("http:");
this.http.setHostName("172.16.222.129");
this.http.setUrlPath("/test");
this.http.setParams({"key":"123","ere":"3243"});
this.http.setPort(3003);
this.http.setIsPost(0);
return new Promise((resolve, reject)=>{
this.http.sendRequest().then((res)=>{
resolve(res);
}).catch((err)=>{
reject(err);
});
});
}
}

module.exports = Request;

测试:

1
2
3
4
5
6
7
8
var Requestrequire("request.js");
var request = new Request();

request.getTest().then((res)=>{
    console.log(res);
}).catch((err)=>{
    console.log(err);
});