reactjshttpsslvps

VPS backend server on be http instead of https


I got a website on built on react and the domain is being hosted on godaddy VPS as well. I am not well versed on server administration. I have CPANEL and WHM through Godaddy VPS server.

My frontend react app

const handleSubmit = async (e) => {
    e.preventDefault();
    try {
        const response = await fetch('https://example.com:8443/send-email', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ email })
        });

And my backend ExpressJS

app.post('/send-email', (req, res) => { const { email } = req.body;

const mailOptions = {
    from: 'test@example.com',
    to: email,
    subject: 'Formatted Email',
    html: `
        <h1>This is a formatted email</h1>
        <p>This email contains some formatted content.</p>
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
        <p>You can also include links: <a href="https://example.com">Example Link</a></p>
    `
};

I am able to curl and send a test to http://example.com:3001/send-email and not https://example.com:8443/send-email. Http vs Https.

Curl to HTTPS will result in curl: (35) error:0A00010B:SSL routines::wrong version number

Curl to HTTP will result in success.

I am not sure what control or made my backend service go to HTTP while my website is on HTTPS and if you attempt to go to http it will be forced to redirect to https.


Solution

  • To communicate with back-end server with https protocol on Express, we have to use the https package. And here are some example code for https communication.

    const express = require('express');
    const https = require('https');
    const fs = require('fs');
    const path = require('path');
    
    const app = express();
    
    const httpsOptions = {
      key: fs.readFileSync(path.join(__dirname, 'ssl', 'server.key')),
      cert: fs.readFileSync(path.join(__dirname, 'ssl', 'server.crt')),
      // If you have a CA (Certificate Authority) chain, include it here
      // ca: [fs.readFileSync(path.join(__dirname, 'ssl', 'ca1.crt')),
      //     fs.readFileSync(path.join(__dirname, 'ssl', 'ca2.crt'))]
    };
    
    https.createServer(httpsOptions, app).listen(443, () => {
      console.log('HTTPS Server running on port 443');
    });
    

    In this example, you'll need to have the server.key and server.crt files in your ssl directory. These files are for SSL certification.

    Please reference this url. Enabling HTTPS on express.js