Node.JS,Express和Heroku - 如何处理HTTP和HTTPS? [英] Node.JS, Express and Heroku - how to handle HTTP and HTTPS?
问题描述
我必须做很多AJAX请求。其中一些需要通过HTTPS协议(一些不需要)来保护。
所以,我的服务器应该同时使用HTTP和HTTPS。
它也应该在本地机器上运行(通常使用nodemon)和Heroku。
据我所知,Heroku给你一个单一的端口(process.env.PORT)你可以听,并通过代理处理所有的请求(所以,你的应用程序正在听这个端口,而不是关心原型?)
所以,我得到这个正确的 - 我应该有一些不同的代码开发机器和Heroku?
像
...
app = express()
...
如果process.env.NODE_ENV =='
app.listen(process.env.PORT)
else
https = require('https')
http = require('http')
http .createServer(app).listen(5080)#一些本地端口
options = {
key:fs.readFileSync('key.pem'),
cert:fs.readFileSync('cert .pem')#我的自签名文件
}
https.createServer(options,app).listen(5443)#一些不同的本地端口
这是处理这个问题的正确方法吗?
这些天看起来很死(希望我错了)
答案是:
a)这是处理它的方式
b)检查您是否处于安全模式的方式取决于环境:
if process.env.NODE_ENV =='production'
is_secure =(req) - >
req.headers ['x-forwarding-proto'] =='https'
else
is_secure =(req) - > req.secure
添加
如果您要强制HTTPS :
redirect_to_https =(req,res,next) - >
如果不是is_secure(req)
res.redirect config.SECURE_DOMAIN + req.url
else
next()
app
。使用(redirect_to_https)
I have an app which is quite normal Express app - simple server logic, views, lots of client-side JS. I have to do many AJAX requests. Some of them need to be secured by HTTPS protocol (some needn't).
So, my server should work with both HTTP and HTTPS. It should also work o both the local machine (ran with nodemon normally) and on Heroku.
As far as I understood, Heroku gives you a single port (process.env.PORT) you can listen to, and handles all requests through the proxy (so, you app is listening to this port and not bothering about the proto - right?)
So, am I getting this right - I should have some different code for dev machine and Heroku?
Like
...
app = express()
...
if process.env.NODE_ENV == 'production'
app.listen(process.env.PORT)
else
https = require('https')
http = require('http')
http.createServer(app).listen(5080) # some local port
options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem') # my self-signed files
}
https.createServer(options, app).listen(5443) # some different local port
Is it the proper way to deal with this?
Well, community looks quite dead these days (hope I'm wrong)
The answer is:
a) yes, this is the way to deal with it
b) the way to check if you are in secure mode or not depends on the environment as well:
if process.env.NODE_ENV == 'production'
is_secure = (req) ->
req.headers['x-forwarded-proto'] == 'https'
else
is_secure = (req) -> req.secure
ADD If you wish to force HTTPS:
redirect_to_https = (req, res, next) ->
if not is_secure(req)
res.redirect config.SECURE_DOMAIN + req.url
else
next()
app
.use(redirect_to_https)
这篇关于Node.JS,Express和Heroku - 如何处理HTTP和HTTPS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!