1. 程式人生 > >nodejs之http模組

nodejs之http模組

nodejs伺服器端

const http = require('http');

const server = http.createServer(function (req, res) {

res.writeHead(200, {

'content-type': 'text/plain'

});

res.end('hello node.js');

 

});

server.listen(3000, function () {

console.log('listening port 3000')

})

或者

const http = require('http');

const server=new http.Server();

server.on('request',function (req, res) {

res.writeHead(200, {

'content-type': 'text/plain'

});

res.end('hello node.js');

 

});

server.listen(3000, function () {

console.log('listening port 3000')

})

 

 

const http = require('http');

const server = http.createServer(function (req, res) {

let data = '';

req.on('data', function (chunk) {

data += chunk;

 

});

req.on('end', function () {

let method = req.method;

// headers是物件,需要轉成字元才能打印出來

let headers = JSON.stringify(req.headers);

let url = req.url;

let httpVersion = req.httpVersion;

res.writeHead(200, {

'content-type': 'text/html'

});

let dataHtml = '<p>data:' + data + '</p>'

let methodHtml = '<p>method:' + method + '</p>'

let headersHtml = '<p>headers:' + headers + '</p>'

let urlHtml = '<p>url:' + url + '</p>'

let httpVersionHtml = '<p>httpVersion:' + httpVersion + '</p>'

let resData = dataHtml + methodHtml + headersHtml + urlHtml + httpVersionHtml

res.end(resData)

})

 

})

server.listen(3000, function () {

console.log('listening port 3000')

})

 

客戶端

 

 

 

const http=require('http');

let reqData=''

http.request({

'host':'192.168.3.72',

'port':'3000',

'method':'get'

},function(res){

res.on('data',function(chunk){

reqData+=chunk;

});

res.on('end',function(){

console.log(reqData);

})

}).end();

 

先把伺服器啟動,然後再啟動客戶端,客戶端通過get請求伺服器資料。

const http=require('http');

let reqData=''

http.get({

'host':'192.168.3.72',

'port':'3000'

},function(res){

res.on('data',function(chunck){

reqData+=chunck

});

res.on('end',function(){

console.log(reqData)

})

}).end();

tip:響應的操作都是在get請求中的。

 

 

 

const http = require('http');

let reqData = '';

let option = {

'host': '192.168.3.72',

'port': '6000'

}

const req = http.request(option);

req.on('response', function (res) {

res.on('data', function (chunk) {

reqData += chunk;

});

res.on('end', function () {

console.log(reqData)

});

});