我正在构建一个部署在vercel上的next js网站。
我做了一个通过nodemailer发送邮件的next.js api /api/contact。当我在我的pc上尝试代码时,它工作得很好,但是当我上传到vercel (与github集成)时,我在控制台中得到一个/api/contact的"404 failed to load resource“,它不能工作。
要让next.js应用程序接口在vercel上工作,还需要做更多的配置吗?
下面是api调用的代码:
fetch("/api/contact", {
method: "POST",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify(data),
}).then((res) => {发布于 2021-07-17 17:41:42
所以这里是有效的答案:“加载资源失败”在几次部署后消失了,但我仍然有一个404。问题是transporter.sendMail需要是异步的,我在gmail上遇到了问题,我最终使用了另一个邮件提供商(zoho)。因此,对于任何面临同样问题的人来说,这里有一个有效的代码(可能不是最好的,但它是有效的):
export default async (req, res) => {
require('dotenv').config()
const nodemailer = require('nodemailer');
async function mail() {
console.log('enter async function');
const transporter = nodemailer.createTransport({
name: "smtp.zoho.com",
port: 465,
host: "smtp.zoho.com",
auth: {
user: process.env.mailsender,
pass: process.env.mailpw,
},
secure: true,
})
let mail = await transporter.sendMail({
from: process.env.mailsender,
to: process.env.mailreceive,
subject: `${req.body.message}`,
text: `${req.body.message}`,
html: `<div><p>${req.body.message}</p></div>`
});
}
try {
console.log('sending mail');
await mail();
res.status(200);
console.log('mail should be sent');
} catch (error) {
console.log(error);
console.log('error sending mail');
res.status(404);
} finally {
res.end();
};
}
https://stackoverflow.com/questions/68338829
复制相似问题