服务端
const http = require('http');
http.createServer((request,response)=>{
request.on('data',(chunk)=>{
console.log('data:'+chunk);
});
request.on('end',()=>{
console.log(request.method);
console.log(JSON.stringify(request.headers));
console.log('recive request end');
});
request.on('close',()=>{
console.log('recive request close');
});
response.writeHead(200,{"Content-type":"text-plain;charset:UTF8"});
response.end("Hello,Node.js!");
}).listen(3000);
console.log("Server Run");
这段代码主要是在3000端口启用服务器,在接收到请求之后,返回200状态码,并返回"Hello,Nodejs"文本。其中,request.on('data',(res)=>{...})是一个请求体数据到来时会触发的事件,事件会返回chunk参数,表示接受的数据。request.on('end',(res)=>{...})是请求体传输完毕会触发的事件。request.on('close',(res)=>{...})是用户请求结束时会触发的事件。接下来看客户端的代码。
客户端
const http = require('http');
let reqData = '';
const req = http.request({
// 'hostname':'www.baidu.com',
'host': '127.0.0.1',
'port': 3000,
// 'port':80,
'method':'GET'
}, (res) => {
// console.log(res);
res.on('data', (chunk) => {
reqData += chunk;
});
res.on('end', () => {
console.log(reqData);
console.log('request end...');
});
});
req.end();
req.on("error", function (err) {
console.log(err.message);
});
http.request是一个向服务端发起请求的方法,其中的配置字段有host(主机,例如127.0.0.1),hostname(域名),port(端口,默认80),method(请求方法,默认为GET),path(请求相对于根的路径,默认是'/'),headers等。其中该方法返回的方法中,可以用request.write()方法发送请求数据,并res.end()结束请求,应始终指定res.end()方法,不然不会获得返回,之前在这里纠结很久。
请求效果
服务器端:
客户端: