Node.js Express项目配置HTTPS后无法访问localhost:3000,需如何修改以启用HTTPS服务?
Let's break down the issues in your code and fix them step by step so your HTTPS server starts properly and is accessible.
1. Critical Mistake: You're Starting an HTTP Server Instead of HTTPS
Looking at your code, you create an HTTPS server with https.createServer(options, app) but never actually start it. Instead, you call app.listen(PORT2) which launches a regular HTTP server on port 3000. That's why you can't reach the HTTPS endpoint.
Fix: Replace the app.listen call with starting the HTTPS server directly:
// Remove this line: app.listen(PORT2, () => success({ message: `Server : ${PORT2}`, badge: true }) ); // Start the HTTPS server instead https.createServer(options, app).listen(PORT2, () => { success({ message: `HTTPS Server running on port : ${PORT2}`, badge: true }); });
2. Verify Certificate File Paths
Relative paths can cause issues depending on where you run your server from. For reliability, use absolute paths with __dirname to ensure Node.js finds your certificate files:
const path = require('path'); // Add this at the top of your file const options = { key: fs.readFileSync(path.join(__dirname, './https/key.pem')), cert: fs.readFileSync(path.join(__dirname, './https/cert.pem')) };
Note: You don't need .toString() here—fs.readFileSync returns a Buffer, which is fully compatible with HTTPS server options.
3. Ensure .env Variables Are Loaded
If your PORT2 is stored in a .env file, double-check that your ./config file is loading environment variables with dotenv. If not, add this line at the top of your main server file (or config file):
require('dotenv').config();
Then in your config file, export PORT2 like this to fall back to a default if the env variable is missing:
module.exports = { PORT2: process.env.PORT2 || 3000, DB: process.env.DB // Your database config };
4. Trust the Self-Signed Certificate in Your Browser
Self-signed certificates (generated with openssl) trigger security warnings in browsers. When you visit https://localhost:3000:
- Click "Advanced" in the warning page
- Choose to proceed to the site (this trusts the certificate temporarily or permanently, depending on your browser)
Full Corrected Server Code Snippet
Here's how your main file should look after applying all fixes:
const cors = require("cors"); const exp = require("express"); const bp = require("body-parser"); var passport = require("passport"); const https = require('https'); const fs = require('fs'); const path = require('path'); // Added path module const { connect } = require("mongoose"); const { success, error } = require("consola"); require('./middlewares/passport'); require('dotenv').config(); // Load env variables const { DB, PORT2 } = require("./config"); const options = { key: fs.readFileSync(path.join(__dirname, './https/key.pem')), cert: fs.readFileSync(path.join(__dirname, './https/cert.pem')) }; // Initialisation const app = exp(); // Middlewares app.use(cors()); app.use(bp.json()); app.use(passport.initialize()); require("./middlewares/passport")(passport); app.use("/api/users", require("./routes/users")); app.use("/api/forum", require("./routes/forumRoute")); app.use("/api/comments", require("./routes/commentRoute")); // Start HTTPS server https.createServer(options, app).listen(PORT2, () => { success({ message: `HTTPS Server running on port : ${PORT2}`, badge: true }); }); const startApp = async () => { try { await connect(DB, { useFindAndModify: true, useUnifiedTopology: true, useNewUrlParser: true, }); success({ message: `Erfolgreich verbunden mit der Datenbank \n${DB}`, badge: true }); } catch (err) { error({ message: ` \n${err}`, badge: true }); setTimeout(() => startApp(), 5000); // Add delay to avoid infinite connection retries } }; startApp();
I added a setTimeout in the database retry logic to prevent overwhelming your database with immediate repeated connection attempts if the initial connection fails.
内容的提问来源于stack exchange,提问作者Deezer

