gpt4 book ai didi

node.js - 如何将来自 Express 的路由用于 HTTPS?

转载 作者:搜寻专家 更新时间:2023-10-31 22:22:30 24 4
gpt4 key购买 nike

我正在向我的 nodeJS 服务器启用 https 请求。但是我想使用我可以从具有该 8080 端口的 http 请求接收到具有该 443 端口的 https 的相同路由。

http://api.myapp.com:8080/api/waitlist/join成功了 https://api.myapp.com:443/api/waitlist/join不是我在代码中遗漏了什么以使用与 httpsServer 的“app”相同的路由?

var fs              = require('fs');
var https = require('https');
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cors = require('cors');
var config = require('./config');

// Configure app to use bodyParser()
[...]
// Configure the CORS rights
app.use(cors());

// Enable https
var privateKey = fs.readFileSync('key.pem', 'utf8');
var certificate = fs.readFileSync('cert.pem', 'utf8');

var credentials = {
key: privateKey,
cert: certificate
};

var httpsServer = https.createServer(credentials, app);

// Configure app port
var port = process.env.PORT || config.app.port; // 8080

// Configure database connection
[...]

// ROUTES FOR OUR API
// =============================================================================

// Create our router
var router = express.Router();

// Middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('>>>> Something is happening. Here is the path: '+req.path);
next();
});

// WAITLIST ROUTES ---------------------------------------
// (POST) Create Email Account --> Join the waitList
router.route('/waitlist/join').post(waitlistCtrl.joinWaitlist);
// And a lot of routes...


// REGISTER OUR ROUTES -------------------------------
// All of our routes will be prefixed with /api
app.use('/api', router);



// START THE SERVER
// =============================================================================
app.listen(port);
httpsServer.listen(443);

谢谢!

最佳答案

使用 API docs对于 .listen 我自己有类似需求的项目,并查看您的代码,我认为两个快速更改应该有效:

1) 将 var http = require('http'); 添加到您的其他需求顶部。

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

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

(如果可行,您还可以删除对 httpsServer 的引用。)

关于node.js - 如何将来自 Express 的路由用于 HTTPS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38112643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com