提问人:xento 提问时间:10/31/2023 更新时间:10/31/2023 访问量:14
nodemailer 不使用 api-gateway-url/dev/submit 发送
nodemailer not sending with api-gateway-url/dev/submit
问:
我的 express.js nodemailer 有问题,因为当我使用 /submit 时,它适用于本地主机,但是当我使用 api 网关 url 时,它不适用于本地主机和上传的网站。顺便说一句,我使用 aws api 网关。
这是我的 express.js 中的我的应用程序.js
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const path = require('path');
const app = express();
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname)); // Serve static files
// Nodemailer transporter setup
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: 'my-email',
clientId: 'number.apps.googleusercontent.com',
clientSecret: 'number',
refreshToken: 'number',
accessToken: 'number',
expires: 1484314697598
}
});
app.get('my-api-url/dev/submit', (req, res) => {
console.log('GET request received at /');
res.sendFile(path.join(__dirname, 'contact.html'));
});
app.post('my-api-url/dev/submit', (req, res) => {
console.log('POST request received at /submit');
let formData = req.body;
// Format the form data as columnar text
let emailContent = Object.keys(formData).map(key => {
return `${key}: ${formData[key]}`;
}).join('\n');
let mailOptions = {
from: 'my-personal-email',
to: 'my-other-personal-email',
subject: 'Form Submission',
text: emailContent
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error('Error sending email:', error);
res.send('Failed to send email. Please try again later.');
} else {
console.log('Email sent:', info.response);
res.redirect('contact.html?submitted=true');
}
});
});
app.use((req, res) => {
console.log(`Route not found: ${req.url}`);
res.status(404).sendFile(path.join(__dirname, '404.html'));
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
这是我的风格.js中的代码
document.addEventListener('DOMContentLoaded', function() {
const form = document.querySelector('form');
const submitButton = document.querySelector('input[type="submit"]');
form.addEventListener('submit', async function(event) {
event.preventDefault(); // Prevent the default form submission
try {
const formData = new FormData(form);
const response = await fetch('my-api-url/dev/submit', {
method: 'POST',
body: formData
});
if (response.ok) {
submitButton.value = 'Submitted';
submitButton.disabled = true;
} else {
throw new Error('Error sending form data');
}
} catch (error) {
console.error('Error:', error);
alert('Error submitting form. Please try again.');
}
});
});
这是我的 AWS 函数的代码
/*
Copyright 2017 - 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
*/
const express = require('express')
const bodyParser = require('body-parser')
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')
// declare a new express app
const app = express()
app.use(bodyParser.json())
app.use(awsServerlessExpressMiddleware.eventContext())
// Enable CORS for all methods
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "*")
next()
});
/**********************
* Example get method *
**********************/
app.get('/submit', function(req, res) {
// Add your code here
res.json({success: 'get call succeed!', url: req.url});
});
/****************************
* Example post method *
****************************/
app.post('/submit', function(req, res) {
// Add your code here
res.json({success: 'post call succeed!', url: req.url, body: req.body})
});
app.post('/submit/*', function(req, res) {
// Add your code here
res.json({success: 'post call succeed!', url: req.url, body: req.body})
});
/****************************
* Example put method *
****************************/
app.put('/submit', function(req, res) {
// Add your code here
res.json({success: 'put call succeed!', url: req.url, body: req.body})
});
app.put('/submit/*', function(req, res) {
// Add your code here
res.json({success: 'put call succeed!', url: req.url, body: req.body})
});
/****************************
* Example delete method *
****************************/
app.delete('/submit', function(req, res) {
// Add your code here
res.json({success: 'delete call succeed!', url: req.url});
});
app.delete('/submit/*', function(req, res) {
// Add your code here
res.json({success: 'delete call succeed!', url: req.url});
});
app.listen(3000, function() {
console.log("App started")
});
// Export the app object. When executing the application local this does nothing. However,
// to port it to AWS Lambda we will create a wrapper around that will load the app from
// this file
module.exports = app
我还没有尝试过任何代码。我希望代码将电子邮件发送到我的另一封电子邮件。它适用于带有 localhost 的 /submit,但当我使用 api-gateway-url/dev/submit 时它不起作用。而且它没有显示任何错误。
答: 暂无答案
评论