Create https service in nodejs and create https in nodejs
Nodejs creates an https service by Wu xueying
Serverr. js
Var https = require ('https'); var fs = require ('fs'); var options = {key: fs. readFileSync ('. /keys/server. key '), cert: fs. readFileSync ('. /keys/server. crt '),}; https. createServer (options, function (req, res) {res. writehead( 200); res. end ("hello world! \ N ") ;}). listen (8000 );
Client. js
Var https = require ('https'); var fs = require ('fs'); var options = {hostname: 'localhost', port: 8000, path :'/', method: 'get', key: fs. readFileSync ('. /keys/client. key '), cert: fs. readFileSync ('. /keys/client. crt '), ca: [fs. readFileSync ('. /keys/ca. crt ')], rejectUnauthorized: false}; options. agent = new https. agent (options); var req = https. request (options, function (res) {res. setEncoding ('utf-8'); res. on ('data', function (d) {console. log (d) ;}); req. end (); req. on ('error', function (e) {console. log (e );});
For details about certificate generation, refer to the previous chapter: Create a TLS service in nodejs.