I try to force my Sails.js WebApp which is hosted on heroku(no nginx installed) from http:// to https:// and use this express middleware in my sail.js app:
In Express it would look like this:
app.use(forceDomain({
hostname: 'www.example.com',
port: 4000,
protocol: 'https'
}));
I tried to use it in my config/http.js file in my sails.js app:
middleware: {
forceDomain: function (req, res, next) {
forceDomain({
hostname: 'www.myurl.com',
port: 4000,
protocol: 'https'
});
next();
},
order: [
'forceDomain',
...
}
I don't understand exactly how to use this "app.use()" thing in sails.js. It is here explained , but I didn't really understand. What I now have doesn't work(no errors, but also no redirecting). How can I fix this?
Installed this module - doesn't work either.
Here is the solution how to force ssl on a sails.js app running on heroku without nginx and without external modules:
In the config/http.js file there is an example of custom middleware:
****************************************************************************
* Example custom middleware; logs each request to the console. *
****************************************************************************
myRequestLogger: function (req, res, next) {
console.log("Requested :: ", req.method, req.url);
next();
}
I made my own custom middleware function which controls if the request is secure, and if not, it redirects the request to https:// or if its a websocket request it redirects the request to wss://
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
}
}
No need for extern modules or hookups. just that function and it works.
Every value in the sails.config.http.middleware
dictionary (besides order
) should be an Express-style middleware function -- that is, a function that accepts req
, res
, and next
, which is exactly what the forcedomain
module returns. The issue in your code is that you're wrapping that function in another function instead of just returning it. Try:
middleware: {
forceDomain: forceDomain({
hostname: 'www.myurl.com',
port: 4000,
protocol: 'https'
}), // <-- the call to `forceDomain()` returns a configured Express middleware fn.
order: [
'forceDomain',
...
}
This assumes that you have var forceDomain = require('forcedomain')
at the top of that file!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.