簡體   English   中英

在sails.js應用中將http://強制為https://

[英]Force http:// to https:// in a sails.js App

我試圖將在heroku(未安裝nginx)上托管的Sails.js WebApp從http://強制轉換為https://,並在我的sail.js應用中使用此快速中間件

在Express中,它看起來像這樣:

app.use(forceDomain({
  hostname: 'www.example.com',
  port: 4000,
  protocol: 'https'
}));

我試圖在我的sails.js應用程序的config / http.js文件中使用它:

middleware: {

        forceDomain: function (req, res, next) {
            forceDomain({
                hostname: 'www.myurl.com',
                port: 4000,
                protocol: 'https'
            });
            next();
        },

        order: [
            'forceDomain',
          ...
}

我不完全了解如何在sails.js中使用此“ app.use()”東西。 在這里進行了解釋 ,但我並沒有真正理解。 我現在所擁有的不起作用(沒有錯誤,也沒有重定向)。 我怎樣才能解決這個問題?

已安裝此模塊 -也不起作用。

以下是解決方案,如何在沒有Nginx和外部模塊的情況下,在heroku上運行的sails.js應用上強制使用ssl:

在config / http.js文件中,有一個自定義中間件的示例:

****************************************************************************
*      Example custom middleware; logs each request to the console.        *  
****************************************************************************

myRequestLogger: function (req, res, next) {
        console.log("Requested :: ", req.method, req.url);
        next();
 }

我制作了自己的自定義中間件功能,該功能控制請求是否安全,如果不安全,它將請求重定向至https://,或者將其重定向為wss://的websocket請求

 order: [
         ...
         'forceSSL',
          ...
         ],


forceSSL: function (req, res, next) {

            if (req.isSocket) {
                return res.redirect('wss://' + req.headers.host + req.url);
            } else if (req.headers["x-forwarded-proto"] == "http") {
                return res.redirect('https://' + req.headers.host + req.url);
            } else {
                next(); //it's already secure
            }
}

無需外部模塊或連接。 只是那個功能,它的工作原理。

sails.config.http.middleware詞典中的每個值(除order之外)都應該是Express風格的中間件函數-即,一個接受reqresnext的函數,這正是forcedomain模塊返回的內容。 代碼中的問題是,您正在將該函數包裝在另一個函數中,而不僅僅是返回它。 嘗試:

middleware: {

    forceDomain: forceDomain({
      hostname: 'www.myurl.com',
      port: 4000,
      protocol: 'https'
    }), // <-- the call to `forceDomain()` returns a configured Express middleware fn.

    order: [
      'forceDomain',
      ...
}

假設您在該文件的頂部具有var forceDomain = require('forcedomain')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM