node.js 创建 https 服务器

1)使用 openssl 命令创建 privatekey.pem 和 certificate.pem:

      openssl genrsa -out privatekey.pem 1024

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

      openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem -days 365 //控制有效期限为365天,默认为30


2)创建https 服务器:

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

var options = {
	key:  fs.readFileSync('./privatekey.pem'),  //带路径的文件名,注意两个文件不要写反了
	cert:fs.readFileSync('./certificate.pem')
};

https.createServer(options, function(req, res) {
	var data = '',
		reqUrl = decodeURIComponent(req.url);
		parse = url.parse(reqUrl, true),
		query = parse.query,
		path = parse.pathname;
	req.on('data', function(chunk) {
		data += chunk; 
	});
	console.log(query);
	res.writeHead(200);
	res.end('hello world\n');
}).listen(8080);

3)运行程序

4)在浏览器中访问:https://localhost:8080?id=1

//注,?号后面的参数随便带,看实际需要



使用post方式访问https服务器:

var https = require('https');
var querystring = require('querystring');
var post_data = querystring.stringify({
	act:'add',
	data:'1'
});
var options = {
	host:'localhost',
	port: 8889,
	path: '/cd02',
	method:'POST',
	rejectUnauthorized: false,  //很多时候不加会访问出错
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded',
		'Content-Length': post_data.length
	}
};

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

req.on('error', function(err) {
	console.dir(err);
})

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



你可能感兴趣的:(node.js)