最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

NodeJS http模塊用法示例【創(chuàng)建web服務(wù)器/客戶端】

 更新時間:2019年11月05日 10:20:28   作者:蒼青浪  
這篇文章主要介紹了NodeJS http模塊用法,結(jié)合實例形式分析了node.js創(chuàng)建web服務(wù)器與客戶端,進(jìn)行HTTP通信的相關(guān)操作技巧,需要的朋友可以參考下

本文實例講述了NodeJS http模塊用法。分享給大家供大家參考,具體如下:

Node.js提供了http模塊,用于搭建HTTP服務(wù)端和客戶端。

創(chuàng)建Web服務(wù)器

/**
 * node-http 服務(wù)端
 */
let http = require('http');
let url = require('url');
let fs = require('fs');
// 創(chuàng)建服務(wù)器
let server = http.createServer((req, res) => {
  // 解析請求
  let pathname = url.parse(req.url).pathname; // 形如`/index.html`
  console.log('收到對文件 ' + pathname + '的請求');
  // 讀取文件內(nèi)容
  fs.readFile(pathname.substr(1), (err, data) => {
    if (err) {
      console.log('文件讀取失?。? + err);
      // 設(shè)置404響應(yīng)
      res.writeHead(404, {
        'Content-Type': 'text/html'
      });
    }
    else {
      // 狀態(tài)碼:200
      res.writeHead(200, {
        'Content-Type': 'text/html'
      });
      // 響應(yīng)文件內(nèi)容
      res.write(data.toString());
    }
    // 發(fā)送響應(yīng)
    res.end();
  });
});
server.listen(8081);
console.log('服務(wù)運(yùn)行在:http://localhost:8081,請訪問:http://localhost:8081/index.html');

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Node http</title>
</head>
<body>
  <h1>Hi~</h1>
</body>
</html>

運(yùn)行server.js,打開瀏覽器訪問。

創(chuàng)建客戶端

client.js

/**
 * node http 創(chuàng)建客戶端
 */
let http = require('http');
// 請求選項
let options = {
  host: 'localhost',
  port: '8081',
  path: '/index.html'
};
// 處理響應(yīng)的回調(diào)函數(shù)
let callback = (res) => {
  // 不斷更新數(shù)據(jù)
  let body = '';
  res.on('data', (data) => {
    body += data;
  });
  res.on('end', () => {
    console.log('數(shù)據(jù)接收完成');
    console.log(body);
  });
}
// 向服務(wù)端發(fā)送請求
let req = http.request(options, callback);
req.end();

運(yùn)行server.js,再運(yùn)行client.js。

希望本文所述對大家node.js程序設(shè)計有所幫助。

相關(guān)文章

最新評論

平塘县| 永宁县| 青田县| 商丘市| 吉隆县| 奇台县| 石林| 石林| 广南县| 沾化县| 黔东| 桐乡市| 梨树县| 沾化县| 镇坪县| 榆树市| 丰城市| 南江县| 成安县| 林口县| 临泽县| 建水县| 尼勒克县| 阿坝| 丹阳市| 手游| 虹口区| 郓城县| 高碑店市| 集安市| 池州市| 南京市| 武城县| 凤台县| 嘉黎县| 唐河县| 凤城市| 冷水江市| 邳州市| 吉水县| 垫江县|