Express(node.js)使用HTTPS和HTTP

我在node.js上使用express(3.0)框架来路由我的应用程序。

我的大部分应用程序都使用http协议,但是我只想通过https服务一条特定的路线。 这是我的API的一部分,它负责注册和authentication用户。

例如:

 app.get('/connect', function(req, res){ // Must be on HTTPS, if not redirect to HTTPS }); app.post('/connect', function(req, res){ // Must be on HTTPS }); app.get('/', function(req, res){ // Must be on HTTP }); app.get('/build', function(req, res){ // Must be on HTTP }); 

如何在同一个应用程序中使用两者? 我正努力在野外find任何这样的例子。

只需将您的app (这实际上是一个请求处理函数)传递给httphttpscreateServer

 var express = require('express') , http = require('http') , https = require('https') , app = express(); http.createServer(app); https.createServer({ ... }, app); 

HTTP和HTTPS请求都通过相同的Express应用程序进行路由。 在路由处理程序中,要检查请求是否通过https进行,请使用req.secure

 app.get('/route', function(req, res) { if (req.secure) { ... } else { res.redirect(301, 'https://example.com/route'); } }); 

作为一个侧面说明,现代智慧认为混合的http / https站点不安全。 您可以通过要求他们通过SSLlogin来保护用户的密码,但是随后的请求切换回http使得攻击者窃取用户的logincookie变得微不足道 。

考虑通过SSLlogin的用户请求所有请求。

尝试这种方法。创build两个快速请求处理程序(app_http和app_https)。

在创buildhttp服务器(http.createServer(app_http))时将app_http作为请求处理程序传递。

在创buildhttps服务器(https.createServer(options,app_https))时将app_https作为请求处理程序传递。

 var express = require('express'), http = require('http'), https = require('https'); var app_http = express(); // this one to handle http request var app_https = express(); // this to handle httpS requests. app_https.get('/connect', function(req, res){ // Must be on HTTPS, if not redirect to HTTPS }); app_https.post('/connect', function(req, res){ // Must be on HTTPS }); app_http.get('/', function(req, res){ // Must be on HTTP }); app_http.get('/build', function(req, res){ // Must be on HTTP }); //call here http.createServer & https.createServer with needed details. 
 const express = require('express'); const app = express(); const fs = require('fs'); const options = { key:fs.readFileSync('./ssl/privkey.pem'), cert:fs.readFileSync('./ssl/allchange.pem') }; const https = require('https').createServer(options,app); const http = require('http').createServer(app); app.get('/',(req,res) => { (req.protocol == 'http') ? res.redirect('https://www.pkred.com/') : // code // More code // End code ; } app.get('/:id',(req,res) => { (req.protocol == 'http') ? res.redirect(`https://www.pkred.com/${req.params.id}`) : // code // More code // End code ; } http.listen(8080,() => console.log('PORT :: 8080')); https.listen(4433,() => console.log('PORT :: 4433'));