DoraCMS

您现在的位置是:首页>文档内容页

文档详情

Node.js API实例讲解——https服务器与客户端

doramart 2015-08-23 22:40:53 NodeJs225290
本节介绍一下创建https服务器和https客户端,其实很简单,按照本节介绍的步骤即可。

https服务器与客户端

本节介绍一下创建https服务器和https客户端,其实很简单,按照本节介绍的步骤即可。

创建https服务器

https和http服务器创建方法一样,都是采用createServer方法,http.createServer创建http服务器,https.createServer创建https服务器,只不过方法参数稍微有些不同。看下面完整的创建https服务器代码。

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

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

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

ok,这就可以了,当客户端通过https://localhost:8000访问时,就可以访问到hello world。

但这里需要两个文件,key.pem和cert.pem,这两个文件是必须的,简单理解这两个文件是用来加密和解密的即可,要创建这两个文件需要系统里安装openssl,下面是创建命令。

第一步

openssl genrsa -out key.pem 1024

这条命令执行后,再执行:

第二步

openssl req -new -key key.pem -out csr.pem

执行命令后终端会有提示输入相关信息,回车即可。然后继续输入一行命令。

第三步

openssl x509 -req -in csr.pem -signkey key.pem -out cert.pem

完成后,就会生成key.pem和cert.pem两个文件,复制到程序的同级目录。

最后通过 https://localhost:8000/ 访问即可。

https 除了以上介绍的配置不同外,其他方面都和http服务器一模一样,这里就不做介绍了,可参看“网络系统”一章。

下面介绍一下https客户端

创建https客户端

当然可以用浏览器作为https客户端,而node.js中也可以创建https客户端。

https客户端和http一模一样,下面简单做个https客户端程序。

var https = require('https');
https.get(
    "https://raw.github.com/brighthas/jsdm/master/index.js",
    function(res){
        res.on("data",function(chunk){
            console.log(chunk.toString());
        })
});

文章评论

取消回复
登录 参与评论

评论列表(