8.2 HTTP客户端

2020-12-06  本文已影响0人  gem_Y

1. 使用request方法向其他网站请求数据

var http = require('http')
var options = {
  hostname: 'www.mcrosoft.com',
  path: '/',
  method: 'GET'
}

var req = http.request(options, function(res) {
  console.log('状态码:' + res.statusCode)
  console.log('响应头:' + JSON.stringify(res.headers))
  res.setEncoding('utf8')
  res.on('data', function(chunk) {
    console.log('响应内容:' + chunk)
  })
})

req.on('socket', function(socket) { //建立连接过程中,当为该连接分配端口时 触发
  req.setTimeout(1000)
  // req.setTimeout(10)
  req.on('timeout', function() {
    req.abort()
  })
})

req.on('error', function(err) {
  if (err.code === 'ECONNRESET') {
    console.log('socket端口超时')
  } else {
    console.log('在请求数据过程中发生错误,错误代码为:' + err.code)
  }
})

req.end()


image.png

2 向本地服务器请求数据

server

var http = require('http')
var server = http.createServer(function(req,res) {
  if (req.url !== '/favicon.ico') {
    req.on('data', function(data) {
      console.log('服务端接收到的数据:' + data)
      // res.end() // 结束客户端请求

      res.write(data)
    })
    req.on('end',function() {
      res.end() // 当客户端请求结束时,同步结束向客户端返回数据
    })
  }
})

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('客户端接收到的数据:' + chunk)
  })
})
req.write('你好。')
req.end('再见。')
上一篇 下一篇

猜你喜欢

热点阅读