提问人:Somil 提问时间:8/17/2023 最后编辑:Somil 更新时间:8/17/2023 访问量:69
在 node js 中使用 API 发送电子邮件
Sending email with API in node js
问:
我一直在尝试创建一个 Web 应用程序,向其新订阅者发送欢迎电子邮件。一个多星期以来,我只遇到了一个问题,我的控制台没有显示任何输出,发送的电子邮件没有成功或失败。我已经检查了我的 API 代码,它运行良好,尝试了所有方法,但不知道为什么终端没有响应 我在终端中尝试节点服务器.js,它说服务器在端口3000上运行,我通过浏览器导航到本地主机3000,并在输入电子邮件后尝试点击订阅,并且终端中没有更新
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const axios = require('axios');
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// trying to create a server to send emails to users who click subscribe button
app.post('/send-welcome-email', async (req, res) => {
const { email } = req.body;
const emailData = {
From: '[email protected]',
To: email,
Subject: 'Welcome to DevLink',
HtmlBody: '<html><head></head><body><p>Welcome to DevLink, thanks for jooining our platform!</p></body></html>'
};
try {
const response = await axios.post('https://api.postmarkapp.com/email', emailData, {
headers: {
'Authorization': `MY_API_TOKEN`,
'Accept': 'application/json',
'content-type': 'application/json'
}
});
res.status(200).send('Email sent');
} catch (error) {
console.error(error);
res.status(500).send('Something went wrong');
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
}
.container {
max-width: 400px;
margin: 0 auto;
padding: 20px;
background-color: #ffffff;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
border-radius: 5px;
margin-top: 50px;
}
h1 {
font-size: 24px;
margin-bottom: 10px;
}
form {
display: flex;
flex-direction: column;
}
label {
font-size: 16px;
margin-bottom: 5px;
}
input[type="email"] {
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
background-color: #007bff;
color: #ffffff;
border: none;
padding: 10px;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>DevLink Subscription</title>
</head>
<body>
<div class="container">
<h1>Signup for our daily insider</h1>
<form id="subscription-form">
<label for="email">Enter your email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Subscribe</button>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
答:
1赞
Quentin
#1
您的屏幕截图显示,您正在尝试通过在运行 服务器的同一终端中运行来向服务器发出 HTTP 请求。curl
node
由于终端正在运行,它不接受新的 shell 命令,因此未运行。node
curl
您需要在不同的终端中运行。curl
评论
script.js