nodejs的http模块方法怎么使用

发布时间:2022-01-25 14:14:30 作者:iii
来源:亿速云 阅读:239

这篇文章主要讲解了“nodejs的http模块方法怎么使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“nodejs的http模块方法怎么使用”吧!

nodejs http模块的方法有:1、createServer(),可创造服务器实例;2、listen(),启动服务器监听指定端口;3、setHeader();4、write();5、end();6、get();7、request()等。

nodejs的http模块方法怎么使用

本教程操作环境:windows7系统、nodejs 12.19.0版,DELL G3电脑。

http模块

1 基本用法

1.1 模块属性

1.1.1 HTTP请求的属性

1.2 模块方法

1.2.1 http模块的方法

createServer(callback):创造服务器实例。

1.2.2 服务器实例的方法

listen(port):启动服务器监听指定端口。

1.2.3 HTTP回应的方法

1.3 处理GET请求

Http模块主要用于搭建HTTP服务。使用Node.js搭建HTTP服务器非常简单。

var http = require('http');

http.createServer(function (request, response){
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8080, "127.0.0.1");

console.log('Server running on port 8080.');
$ node app.js

这时命令行窗口将显示一行提示“Server running at port 8080.”。打开浏览器,访问http://localhost:8080,网页显示“Hello world!”
上面的例子是当场生成网页,也可以事前写好网页,存在文件中,然后利用fs模块读取网页文件,将其返回。

var http = require('http');
var fs = require('fs');

http.createServer(function (request, response){
  fs.readFile('data.txt', function readData(err, data) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end(data);
  });
}).listen(8080, "127.0.0.1");

console.log('Server running on port 8080.');

下面的修改则是根据不同网址的请求,显示不同的内容,已经相当于做出一个网站的雏形了。

var http = require("http");
http.createServer(function(req, res) {
  // 主页
  if (req.url == "/") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("Welcome to the homepage!");
  }
	// About页面
  else if (req.url == "/about") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("Welcome to the about page!");
  }
  // 404错误
  else {
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("404 error! File not found.");
  }
}).listen(8080, "localhost");

回调函数的req(request)对象,拥有以下属性。

1.4 处理POST请求

当客户端采用POST方法发送数据时,服务器端可以对dataend两个事件,设立监听函数。

var http = require('http');

http.createServer(function (req, res) {
  var content = "";

  req.on('data', function (chunk) {
    content += chunk;
  });

  req.on('end', function () {
    res.writeHead(200, {"Content-Type": "text/plain"});
    res.write("You've sent: " + content);
    res.end();
  });

}).listen(8080);

data事件会在数据接收过程中,每收到一段数据就触发一次,接收到的数据被传入回调函数。end事件则是在所有数据接收完成后触发。
对上面代码稍加修改,就可以做出文件上传的功能。

"use strict";

var http = require('http');
var fs = require('fs');
var destinationFile, fileSize, uploadedBytes;

http.createServer(function (request, response) {
  response.writeHead(200);
  destinationFile = fs.createWriteStream("destination.md");
  request.pipe(destinationFile);
  fileSize = request.headers['content-length'];
  uploadedBytes = 0;

  request.on('data', function (d) {
    uploadedBytes += d.length;
    var p = (uploadedBytes / fileSize) * 100;
    response.write("Uploading " + parseInt(p, 0) + " %\n");
  });

  request.on('end', function () {
    response.end("File Upload Complete");
  });
}).listen(3030, function () {
  console.log("server started");
});

2 发出请求

2.1 get()

get方法用于发出get请求。

function getTestPersonaLoginCredentials(callback) {
  return http.get({
    host: 'personatestuser.org',
    path: '/email'
  }, function(response) {
    var body = '';

    response.on('data', function(d) {
      body += d;
    });

    response.on('end', function() {
      var parsed = JSON.parse(body);
      callback({
        email: parsed.email,
        password: parsed.pass
      });
    });
  });
},

2.2 request()

request方法用于发出HTTP请求,它的使用格式如下。

http.request(options[, callback])

request方法的options参数,可以是一个对象,也可以是一个字符串。如果是字符串,就表示这是一个URL,Node内部就会自动调用url.parse(),处理这个参数。
options对象可以设置如下属性

var postData = querystring.stringify({
  'msg' : 'Hello World!'
});

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': postData.length
  }
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write(postData);
req.end();

注意,上面代码中,req.end()必须被调用,即使没有在请求体内写入任何数据,也必须调用。因为这表示已经完成HTTP请求
发送过程的任何错误(DNS错误、TCP错误、HTTP解析错误),都会在request对象上触发error事件

3 搭建HTTPs服务器

搭建HTTPs服务器需要有SSL证书。对于向公众提供服务的网站,SSL证书需要向证书颁发机构购买;对于自用的网站,可以自制。
自制SSL证书需要OpenSSL,具体命令如下。

openssl genrsa -out key.pem
openssl req -new -key key.pem -out csr.pem
openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem
rm csr.pem

上面的命令生成两个文件:ert.pem(证书文件)key.pem(私钥文件)。有了这两个文件,就可以运行HTTPs服务器了。
Node.js提供一个https模块,专门用于处理加密访问。

var https = require('https');
var fs = require('fs');
var options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

var a = https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8000);

上面代码显示,HTTPs服务器与HTTP服务器的最大区别,就是createServer方法多了一个options参数。运行以后,就可以测试是否能够正常访问。

curl -k https://localhost:8000

感谢各位的阅读,以上就是“nodejs的http模块方法怎么使用”的内容了,经过本文的学习后,相信大家对nodejs的http模块方法怎么使用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. nodeJS之HTTP
  2. nodejs路由模块使用

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

nodejs http

上一篇:Redis的持久化方式有哪些

下一篇:Ubuntu怎么安装并使用Shutter

相关阅读

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

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