温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

http模块怎么在NodeJS中使用

发布时间:2021-03-18 15:55:06 来源:亿速云 阅读:117 作者:Leah 栏目:web开发

http模块怎么在NodeJS中使用?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

创建Web服务器

/**
 * node-http 服务端
 */
let http = require('http');
let url = require('url');
let fs = require('fs');
// 创建服务器
let server = http.createServer((req, res) => {
  // 解析请求
  let pathname = url.parse(req.url).pathname; // 形如`/index.html`
  console.log('收到对文件 ' + pathname + '的请求');
  // 读取文件内容
  fs.readFile(pathname.substr(1), (err, data) => {
    if (err) {
      console.log('文件读取失败:' + err);
      // 设置404响应
      res.writeHead(404, {
        'Content-Type': 'text/html'
      });
    }
    else {
      // 状态码:200
      res.writeHead(200, {
        'Content-Type': 'text/html'
      });
      // 响应文件内容
      res.write(data.toString());
    }
    // 发送响应
    res.end();
  });
});
server.listen(8081);
console.log('服务运行在: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>
  <h2>Hi~</h2>
</body>
</html>

运行server.js,打开浏览器访问。

创建客户端

client.js

/**
 * node http 创建客户端
 */
let http = require('http');
// 请求选项
let options = {
  host: 'localhost',
  port: '8081',
  path: '/index.html'
};
// 处理响应的回调函数
let callback = (res) => {
  // 不断更新数据
  let body = '';
  res.on('data', (data) => {
    body += data;
  });
  res.on('end', () => {
    console.log('数据接收完成');
    console.log(body);
  });
}
// 向服务端发送请求
let req = http.request(options, callback);
req.end();

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI