如何在HTML页面中展示node-temp-mail库返回的body变量
Hey there! I see you're trying to use node-temp-mail in a browser environment to display emails on your HTML page—let's break down what's going on and how to fix it.
The Core Issue
node-temp-mail is a Node.js-only library—it relies on Node-specific features like require() which aren't supported in browsers. If you run your current JavaScript directly in the browser, you'll get errors immediately because the browser doesn't recognize require().
Let's go over two solid solutions to get your email content displayed on the page:
Solution 1: Use the Temp-Mail Public API Directly (No Node.js Backend Needed)
The node-temp-mail library is just a wrapper around the public Temp-Mail API. You can skip the library entirely and call the API directly from your browser using fetch(). Here's how to adjust your code:
Step 1: Update Your HTML
Add a container to display email content somewhere in your <body> (after your card div works great):
<div id="email-display" style="margin-top: 2rem; padding: 1rem; border: 1px solid #ccc;"> <h3>Your Temporary Emails:</h3> <div id="email-content"></div> </div>
Step 2: Rewrite Your JavaScript (Browser-Friendly)
Replace your current javasquript.js with this code (no require() needed):
// Reuse your random ID generator function function makeid(length) { let result = ''; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charactersLength = characters.length; for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } // Generate your temp email address const emailPrefix = makeid(5); const fullEmail = `${emailPrefix}@temp-mail.org`; // Temp-Mail's default domain // Function to fetch and display emails async function fetchAndDisplayEmails() { const emailContent = document.getElementById('email-content'); try { // Fetch emails from Temp-Mail API const response = await fetch(`https://api.temp-mail.org/request/mail/id/${emailPrefix}/format/json/`); const emails = await response.json(); // Show the generated email first emailContent.innerHTML = `<p>Send test messages here: <strong>${fullEmail}</strong></p>`; // Handle empty inbox case if (emails.length === 0) { emailContent.innerHTML += "<p>No emails yet—send a test message to the address above!</p>"; return; } // Display each email emails.forEach(email => { const emailCard = document.createElement('div'); emailCard.style.marginTop = '1rem'; emailCard.style.padding = '0.75rem'; emailCard.style.backgroundColor = '#f8f9fa'; emailCard.style.borderRadius = '4px'; emailCard.innerHTML = ` <h4>From: ${email.mail_from}</h4> <p><strong>Subject:</strong> ${email.mail_subject}</p> <p><strong>Message:</strong> ${email.mail_text}</p> `; emailContent.appendChild(emailCard); }); } catch (err) { console.error('Error loading emails:', err); emailContent.innerHTML += `<p>Oops! Error loading emails: ${err.message}</p>`; } } // Fetch emails on page load, then refresh every 10 seconds fetchAndDisplayEmails(); setInterval(fetchAndDisplayEmails, 10000);
Solution 2: Use a Node.js Backend as a Proxy
If you really want to keep using node-temp-mail, you'll need a small Node.js server to handle the library calls (since it only works in Node), then have your frontend fetch data from this server.
Step 1: Set Up the Backend
- Create a new project folder, run
npm init -yto initialize it. - Install dependencies:
npm install express cors node-temp-mail - Create a
server.jsfile with this code:
const express = require('express'); const cors = require('cors'); const TempMail = require('node-temp-mail'); const app = express(); app.use(cors()); // Allow cross-origin requests from your frontend // Endpoint to generate email and fetch messages app.get('/get-emails', async (req, res) => { try { // Generate random email prefix function makeid(length) { let result = ''; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charactersLength = characters.length; for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } const address = new TempMail(makeid(5), true); const emailAddress = address.getAddress(); // Wrap callback-based fetchEmails in a promise for async/await const emails = await new Promise((resolve, reject) => { address.fetchEmails((err, body) => { if (err) reject(err); else resolve(body); }); }); res.json({ emailAddress, emails }); } catch (err) { res.status(500).json({ error: err.message }); } }); // Start server on port 3000 app.listen(3000, () => { console.log('Server running at http://localhost:3000'); });
Step 2: Update Your Frontend
- Add the same email display container to your HTML as in Solution 1.
- Update your
javasquript.jsto fetch from the backend:
async function fetchEmailsFromBackend() { const emailContent = document.getElementById('email-content'); try { const response = await fetch('http://localhost:3000/get-emails'); const data = await response.json(); emailContent.innerHTML = `<p>Send test messages here: <strong>${data.emailAddress}</strong></p>`; if (data.emails.length === 0) { emailContent.innerHTML += "<p>No emails yet—send a test message to the address above!</p>"; return; } // Display each email data.emails.forEach(email => { const emailCard = document.createElement('div'); emailCard.style.marginTop = '1rem'; emailCard.style.padding = '0.75rem'; emailCard.style.backgroundColor = '#f8f9fa'; emailCard.style.borderRadius = '4px'; emailCard.innerHTML = ` <h4>From: ${email.mail_from}</h4> <p><strong>Subject:</strong> ${email.mail_subject}</p> <p><strong>Message:</strong> ${email.mail_text}</p> `; emailContent.appendChild(emailCard); }); } catch (err) { console.error('Error:', err); emailContent.innerHTML += `<p>Oops! Error loading emails: ${err.message}</p>`; } } // Fetch on load and refresh every 10 seconds fetchEmailsFromBackend(); setInterval(fetchEmailsFromBackend, 10000);
Step 3: Run the Backend
Start your server with node server.js, then open your HTML file in the browser—it will now fetch data from your Node.js server, which uses node-temp-mail under the hood.
Quick Notes
- For Solution 1, double-check the Temp-Mail API endpoint if you run into issues—they occasionally update their API structure.
- For Solution 2 in production, restrict CORS to your frontend domain (don't use
cors()with no restrictions) and host your backend on a service like Vercel or Heroku.
内容的提问来源于stack exchange,提问作者user19055220

