node.js – 如何使用Express for HTTPS的路由?

前端之家收集整理的这篇文章主要介绍了node.js – 如何使用Express for HTTPS的路由?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在向我的nodeJS服务器启用https请求.但我想使用相同的路由,我可以从具有该8080端口的http请求接收到具有该443端口的https.

http://api.myapp.com:8080/api/waitlist/join是成功的
https://api.myapp.com:443/api/waitlist/join不是
我在代码中错过了什么来使用与httpsServer的’app’相同的路由?

  1. var fs = require('fs');
  2. var https = require('https');
  3. var express = require('express'); // call express
  4. var app = express(); // define our app using express
  5. var bodyParser = require('body-parser');
  6. var mongoose = require('mongoose');
  7. var cors = require('cors');
  8. var config = require('./config');
  9.  
  10. // Configure app to use bodyParser()
  11. [...]
  12. // Configure the CORS rights
  13. app.use(cors());
  14.  
  15. // Enable https
  16. var privateKey = fs.readFileSync('key.pem','utf8');
  17. var certificate = fs.readFileSync('cert.pem','utf8');
  18.  
  19. var credentials = {
  20. key: privateKey,cert: certificate
  21. };
  22.  
  23. var httpsServer = https.createServer(credentials,app);
  24.  
  25. // Configure app port
  26. var port = process.env.PORT || config.app.port; // 8080
  27.  
  28. // Configure database connection
  29. [...]
  30.  
  31. // ROUTES FOR OUR API
  32. // =============================================================================
  33.  
  34. // Create our router
  35. var router = express.Router();
  36.  
  37. // Middleware to use for all requests
  38. router.use(function(req,res,next) {
  39. // do logging
  40. console.log('>>>> Something is happening. Here is the path: '+req.path);
  41. next();
  42. });
  43.  
  44. // WAITLIST ROUTES ---------------------------------------
  45. // (POST) Create Email Account --> Join the waitList
  46. router.route('/waitlist/join').post(waitlistCtrl.joinWaitlist);
  47. // And a lot of routes...
  48.  
  49.  
  50. // REGISTER OUR ROUTES -------------------------------
  51. // All of our routes will be prefixed with /api
  52. app.use('/api',router);
  53.  
  54.  
  55.  
  56. // START THE SERVER
  57. // =============================================================================
  58. app.listen(port);
  59. httpsServer.listen(443);

谢谢!

解决方法

使用 API docs for .listen在我自己的项目中有类似的需求,并查看你的代码,我认为两个快速更改应该工作:

1)添加var http = require(‘http’);满足您的其他要求.

2)将应用程序的最后两行更改为:

  1. // START THE SERVER
  2. // =============================================================================
  3. http.createServer(app).listen(port);
  4. https.createServer(credentials,app).listen(443);

(如果此方法有效,您还可以删除对httpsServer的引用.)

猜你在找的Node.js相关文章