小东子的个人技术专栏

Node.js http服务器搭建和发送http的get,post请求

1.Node.js 搭建http服务器

1.1创建server.js

1
2
3
4
5
6
7
8
var http = require('http');
var querystring = require('querystring');
http.createServer(function (request, response) {
console.log('receive request');
response.writeHead(200, { 'Content-Type': 'text-plain' });
response.end('Hello World\n');
}).listen(8124);
console.log("node server start ok port "+8124);

1.2执行 server.js

1
node server.js

1.3服务器启动

如图:
这里写图片描述

通过浏览器地址请求:http://localhost:8124

这里写图片描述

2.发送GET请求

2.1发送get请求通过聚合服务器获取微信新闻数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var http = require('http');
var querystring = require('querystring');
http.get('http://v.juhe.cn/weixin/query?key=f16af393a63364b729fd81ed9fdd4b7d&pno=1&ps=10', function (response) {
var body = [];
console.log(response.statusCode);
console.log(response.headers);
console.log(response);
response.on('data', function (chunk) {
body.push(chunk);
});
response.on('end', function () {
body = Buffer.concat(body);
console.log(body.toString());
});
});

2.2 执行 get_demo.js

1
node get_demo.js

2.3获取的结果打印

这里写图片描述

3.发送POST请求

3.1发送post请求通过聚合服务器获取微信闻数据

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
var http = require('http');
var querystring = require('querystring');
var postData = querystring.stringify({
'key' : 'f16af393a63364b729fd81ed9fdd4b7d',
'pno':'1',
'ps':10
});
var options = {
hostname: 'v.juhe.cn',
path: '/weixin/query',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.')
})
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();

3.2 执行 post_demo.js

1
node post_demo.js

3.3获取的结果打印

这里写图片描述