Request on production stays pending, shows "No 'Access-Control-Allow-Origin' header" error after aborted
Echelpoel opened this issue · comments
I built a microservice which handles a contact form request and sends the data to Mailgun:
index.js:
const { handleSendContactForm } = require('./send-contact-form/handler')
const sendContactFormCors = microCors({ allowMethods: ['OPTIONS', 'POST'] })
module.exports = router(
post('/send-contact-form', rateLimit(sendContactFormCors(handleSendContactForm))),
options('/send-contact-form', rateLimit(sendContactFormCors((req, res) => send(res, 200)))),
)
handler.js:
const RESPONSE_MESSAGES = {
406: 'Invalid contact form data.',
500: 'Something went wrong. Failed to send e-mail.',
200: 'E-mail successfully sent.'
}
const handleSendContactForm = async (req, res) => {
const data = await json(req)
if (!isValidContactForm(data)) {
const statusCode = 406
send(res, statusCode, {
statusCode,
message: RESPONSE_MESSAGES[statusCode],
errors: getContactFormValidationErrors(data)
})
} else {
try {
await sendContactFormEmail(data)
} catch (err) {
const statusCode = 500
send(res, statusCode, {
statusCode,
message: RESPONSE_MESSAGES[statusCode],
})
}
const statusCode = 200
send(res, statusCode, {
statusCode,
message: RESPONSE_MESSAGES[statusCode]
})
}
}
module.exports = {
handleSendContactForm,
}
This is working fine locally (without any cors issues), but when deployed to zeit now, the request status stays pending before aborting:
After aborting I get this error in my console:
Failed to load https://[REMOVED]/send-contact-form: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '[REMOVED]' is therefore not allowed access. The response had HTTP status code 502. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
& in the response of the failed request:
{"status":"502","description":"An error occured with your deployment"}
but nothing shows up in the deployment logs.
This was working perfectly fine before, so I have no idea if this is an issue with my code, micro or the now deployment.
I was able to solve this.
In the sendContactFormEmail
function I used nodemailer
to send an e-mail with Mailgun's SMTP protocol but the request kept being pending and eventually aborted because the instance crashed.
Instead of nodemailer
I used nodemailer-mailgun-transport
and used Mailgun's API to send the e-mail which worked like expected.