1. 使用request方法向其他網(wǎng)站請(qǐng)求數(shù)據(jù)
var http = require('http')
var options = {
hostname: 'www.mcrosoft.com',
path: '/',
method: 'GET'
}
var req = http.request(options, function(res) {
console.log('狀態(tài)碼:' + res.statusCode)
console.log('響應(yīng)頭:' + JSON.stringify(res.headers))
res.setEncoding('utf8')
res.on('data', function(chunk) {
console.log('響應(yīng)內(nèi)容:' + chunk)
})
})
req.on('socket', function(socket) { //建立連接過(guò)程中璧函,當(dāng)為該連接分配端口時(shí) 觸發(fā)
req.setTimeout(1000)
// req.setTimeout(10)
req.on('timeout', function() {
req.abort()
})
})
req.on('error', function(err) {
if (err.code === 'ECONNRESET') {
console.log('socket端口超時(shí)')
} else {
console.log('在請(qǐng)求數(shù)據(jù)過(guò)程中發(fā)生錯(cuò)誤,錯(cuò)誤代碼為:' + err.code)
}
})
req.end()
2 向本地服務(wù)器請(qǐng)求數(shù)據(jù)
server
var http = require('http')
var server = http.createServer(function(req,res) {
if (req.url !== '/favicon.ico') {
req.on('data', function(data) {
console.log('服務(wù)端接收到的數(shù)據(jù):' + data)
// res.end() // 結(jié)束客戶端請(qǐng)求
res.write(data)
})
req.on('end',function() {
res.end() // 當(dāng)客戶端請(qǐng)求結(jié)束時(shí)悠瞬,同步結(jié)束向客戶端返回?cái)?shù)據(jù)
})
}
})
server.listen(1337, 'localhost')
client
var http = require('http')
var options = {
hostname: 'localhost',
port: 1337,
path: '/',
method: 'POST'
}
var req = http.request(options, function(res) {
res.on('data', function(chunk) {
console.log('客戶端接收到的數(shù)據(jù):' + chunk)
})
})
req.write('你好。')
req.end('再見(jiàn)库糠。')