Node.js/Express

Save the following code in a file named server.js:


const express = require('express');
const axios = require('axios');
const path = require('path');
const app = express();
const port = 3000;

app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());

const API_KEY = 'your-api-key-here'; // Securely store this in environment variables or a config file
const API_ENDPOINT = 'https://thumbnail.robinswebdesign.com'; // Thumbnail API endpoint

// Endpoint to handle thumbnail requests
app.post('/thumbnail', async (req, res) => {
    try {
        const { url, screenType } = req.body;
        const response = await axios.post(API_ENDPOINT, {
            url: url,
            screenType: screenType
        }, {
            headers: {
                'Authorization': `Bearer ${API_KEY}`,
                'Content-Type': 'application/json'
            },
            responseType: 'arraybuffer'
        });

        res.set('Content-Type', 'image/png');
        res.send(response.data);
    } catch (error) {
        console.error('Error generating thumbnail:', error.message);
        res.status(500).send('Internal Server Error');
    }
});

// Serve the HTML page
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});
        

Installation & Setup:

  • Install Node.js dependencies:
    npm install express axios
  • Run the server:
    node server.js

PHP

Save the following code in a file named generate_thumbnail.php:

 
            
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $apiKey = 'your-api-key-here';
                $apiEndpoint = 'https://thumbnail.robinswebdesign.com';
            
                $url = $_POST['url'];
                $screenType = 'full'; //Types: full,mobile,tablet
            
                $ch = curl_init($apiEndpoint);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    'Authorization: Bearer ' . $apiKey,
                    'Content-Type: application/json'
                ]);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
                    'url' => $url,
                    'screenType' => $screenType
                ]));
            
               
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            
                $response = curl_exec($ch);
            
                if ($response === false) {
                    $error_msg = curl_error($ch);
                    curl_close($ch);
                    error_log('cURL Error: ' . $error_msg);
                    http_response_code(500);
                    echo 'Internal Server Error: ' . $error_msg;
                    exit;
                }
            
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
            
                if ($httpCode === 200) {
                    header('Content-Type: image/png');
                    echo $response;
                } else {
                    error_log('API Request failed with HTTP Code: ' . $httpCode . ' and Response: ' . $response);
                    http_response_code(500);
                    echo 'Internal Server Error';
                }
            }
           
        

Usage: Use this PHP script on your server to handle POST requests and return thumbnail images.

Python/Flask

Save the following code in a file named server.py:


from flask import Flask, request, Response
import requests

app = Flask(__name__)

API_KEY = 'your-api-key-here'  # Securely store this in environment variables or a config file
API_ENDPOINT = 'https://thumbnail.robinswebdesign.com'  # Thumbnail API endpoint

@app.route('/thumbnail', methods=['POST'])
def generate_thumbnail():
    try:
        data = request.get_json()
        url = data.get('url')
        screen_type = data.get('screenType')

        headers = {
            'Authorization': f'Bearer {API_KEY}',
            'Content-Type': 'application/json'
        }
        response = requests.post(API_ENDPOINT, json={
            'url': url,
            'screenType': screen_type
        }, headers=headers)

        if response.status_code == 200:
            return Response(response.content, mimetype='image/png')
        else:
            return 'Internal Server Error', 500
    except Exception as e:
        print(f'Error generating thumbnail: {str(e)}')
        return 'Internal Server Error', 500

if __name__ == '__main__':
    app.run(port=3000)
        

Installation & Setup:

  • Install Python dependencies:
    pip install flask requests
  • Run the server:
    python server.py

Client-Side Code Example

Use the following HTML and JavaScript code to interact with the server and display thumbnails:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Thumbnail Generator</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .showcase {
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <h1>Thumbnail Generator</h1>
    <div class="showcase">
        <h2>Generate Thumbnail</h2>
        <input type="text" id="urlInput" placeholder="Enter URL here" />
        <button onclick="generateThumbnail()">Generate Thumbnail</button>
        <br><br>
        <img id="thumbnailImage" alt="Thumbnail will appear here" style="max-width: 100%; height: auto;" />
    </div>

    <script>
        function generateThumbnail() {
            const apiEndpoint = '/thumbnail'; // Your server-side endpoint

            const url = document.getElementById('urlInput').value; // Get URL from input field
            const screenType = 'full'; // Choose 'full', 'mobile', or 'tablet'

            const data = {
                url: url,
                screenType: screenType
            };

            fetch(apiEndpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.blob())
            .then(blob => {
                const imageUrl = URL.createObjectURL(blob);
                document.getElementById('thumbnailImage').src = imageUrl;
            })
            .catch(error => console.error('Error:', error));
        }
    </script>
</body>
</html>
        

Instructions:

  • Place the client-side code in an HTML file.
  • Ensure that your server (Node.js, PHP, or Python) is running and accessible from the client.
  • Update the API endpoint URLs and keys in your server-side code as necessary.
footer-frame