大佬教程收集整理的这篇文章主要介绍了node.js – Nodejs在同一端口上的HTTP和HTTPS,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个运行在HTTPS和端口3001上的NodeJS服务器。现在我想获取端口3001上所有传入的HTTP请求,并将它们重定向到相同的URL但通过HTTPS。
这是必须的。不是吗
谢谢!
按照约定,当您请求http://127.0.0.1时,您的浏览器将尝试连接到端口80.如果您尝试打开https://127.0.0.1,您的浏览器将尝试连接到端口443.因此,为了确保所有流量只需传统的方式来监听http上的端口80,重定向到https,我们已经有一个监听器用于https 443的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.end('secure!'); }).listen(443); // Redirect from http port 80 to https var http = require('http'); http.createServer(function (req,res) { res.writeHead(301,{ "Location": "https://" + req.headers['host'] + req.url }); res.end(); }).listen(80);
用https测试
$ curl https://127.0.0.1 -k secure!
用http:
$ curl http://127.0.0.1 -i HTTP/1.1 301 Moved Permanently Location: https://127.0.0.1/ Date: Sun,01 Jun 2014 06:15:16 GMT Connection: keep-alive transfer-encoding: chunked
如果你必须在同一个端口上听
在同一个端口上没有简单的http / https监听方式。你最好打算在一个简单的网络套接字上创建代理服务器,这个网络管道根据传入连接的性质(http对https)来管理(http或https)。
这是完整的代码(基于https://gist.github.com/bnoordhuis/4740141)。它监听localhost:3000并将其管道到http(这又将其重定向到https),或者如果进入连接在https中,则只将其传递给https处理程序
var fs = require('fs'); var net = require('net'); var http = require('http'); var https = require('https'); var baseAddress = 3000; var redirectAddress = 3001; var httpsAddress = 3002; var httpsOptions = { key: fs.readFileSync('./key.pem'),cert: fs.readFileSync('./cert.pem') }; net.createServer(tcpConnection).listen(baseAddress); http.createServer(httpconnection).listen(redirectAddress); https.createServer(httpsOptions,httpsConnection).listen(httpsAddress); function tcpConnection(conn) { conn.once('data',function (buf) { // A TLS handshake record starts with byte 22. var address = (buf[0] === 22) ? httpsAddress : redirectAddress; var proxy = net.createConnection(address,function () { proxy.write(buf); conn.pipe(proxy).pipe(conn); }); }); } function httpconnection(req,res) { var host = req.headers['host']; res.writeHead(301,{ "Location": "https://" + host + req.url }); res.end(); } function httpsConnection(req,res) { res.writeHead(200,{ 'Content-Length': '5' }); res.end('HTTPS'); }
作为测试,如果您使用https连接,您将获得https处理程序:
$ curl https://127.0.0.1:3000 -k HTTPS
如果您将其与http连接,您将获得重定向处理程序(只需将您转到https处理程序):
$ curl http://127.0.0.1:3000 -i HTTP/1.1 301 Moved Permanently Location: https://127.0.0.1:3000/ Date: Sat,31 May 2014 16:36:56 GMT Connection: keep-alive transfer-encoding: chunked
以上是大佬教程为你收集整理的node.js – Nodejs在同一端口上的HTTP和HTTPS全部内容,希望文章能够帮你解决node.js – Nodejs在同一端口上的HTTP和HTTPS所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。