node.js創(chuàng)建一個簡單的http服務(wù)

// 服務(wù)器就是一臺24h不斷電的電腦
// ip地址用來定位計算機,端口號用來定位服務(wù)器內(nèi)具體的應(yīng)用程序(QQ、微信。。。)。通過端口號才能找到對應(yīng)的應(yīng)用程序
//凡是通信的軟件一定會有ip地址和端口號,端口號范圍0-65535
//req.url:獲取到的是端口號之后的那部分字符串,也就是說url是以'/'開頭的
//1.引入http模塊
var http = require('http')
//2.使用http.creatServer()創(chuàng)建一個Web服務(wù)器
var server = http.createServer()
//3.注冊request事件,發(fā)送請求,服務(wù)器接收到請求
//3.1 request請求事件處理函數(shù)需要傳遞兩個參數(shù)request(請求對象)和response(響應(yīng)對象)
server.on('request', function (request, response) {
  console.log('客戶端發(fā)送的請求路徑是:' + request.url);
  // console.log('請求我的客戶端端口號:'+request.socket.remotePort);
//3.2responce有個方法write,可以給客戶端發(fā)送數(shù)據(jù),但必須以end()結(jié)束
  if (request.url === '/login') {
    response.setHeader('Content-Type', 'text/plain;charset=utf-8')
    response.write('請登錄')
    response.end()
  } else if (request.url === '/register') {
    response.setHeader('Content-Type', 'text/plain;charset=utf-8')
    response.write('請注冊')
    response.end()
  } else if (request.url === '/products') {
    //返回商品信息
    var products = [{
      name: '蘋果',
      price: 30
    },
      {
        name: '菠蘿',
        price: 40
      },
      {
        name: '香蕉',
        price: 20
      }
    ]
    //返回的的內(nèi)容只能是二進制數(shù)據(jù)(buffer)或字符串,其它都不行
    // 解決中文亂碼
    //在服務(wù)端默認(rèn)發(fā)送的數(shù)據(jù)格式utf-8格式,而瀏覽器不知道服務(wù)端發(fā)送數(shù)據(jù)的格式,它默認(rèn)的是GBK,所以會出現(xiàn)亂碼,解決辦法如下
    //在http協(xié)議中,Content-Type用來告訴對方我發(fā)送的數(shù)據(jù)格式是什么類型的
    //text/plain:普通文本 text/html:html文本 text/xml:xml文本
    response.setHeader('Content-Type', 'text/plain;charset=utf-8')
    //JSON.stringify():將數(shù)組或者對象轉(zhuǎn)換為字符串
    response.write(JSON.stringify(products))
    response.end()
  }
})
// 4.綁定端口號,啟動服務(wù)器
server.listen(4000, function () {
  console.log('已啟動服務(wù)器');
})

http的運用

var http = require('http')
var fs = require('fs')
var server = http.createServer()
server.on('request',function (req,res) {
  if(req.url === '/bosspin'){
    fs.readFile('./1.html',function (err,data) {
        if(!err){
          res.setHeader('Content-Type','text/html;charset=utf-8')
          //res.end()支持兩種數(shù)據(jù)類型,一種是二進制數(shù)據(jù),另一種是字符串
          res.end(data)
        }
    })
  }else if(req.url === '/bosspin/pic'){
    fs.readFile('./hello.jpg',function (err,data) {
      if(!err){
        res.setHeader('Content-Type','image/jpeg')
        //res.end()支持兩種數(shù)據(jù)類型,一種是二進制數(shù)據(jù),另一種是字符串
        res.end(data)
      }
    })
  }else if(req.url.indexOf('/hello') === 0){
    fs.readFile('.'+req.url,function (err,data) {
      if(!err){
        res.setHeader('Content-Type','image/jpeg')
        res.end(data)
      }
    })
  }
})
server.listen(4100,function () {
  console.log('已啟動服務(wù)器1');
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容