So, I am creating a Cloudflare worker to send an email through an HTML form. Below is the JS code that I am using(I modified it a bit from the CF blog to use an HTML form instead to send an email).
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
})
let body = {};
async function handleRequest(request) {
let content = "just drop if it fails...okay ?";
for( var i of request.headers.entries() ) {
content += i[0] + ": " + i[1] + "n";
}
let send_request = new Request("https://api.mailchannels.net/tx/v1/send", {
"method": "POST",
"headers": {
"content-type": "application/json",
},
"body": JSON.stringify({
"personalizations": [
{ "to": [ {"email": body.email,
"name": body.name}]}
],
"from": {
"email": "[email protected]",
"name": "Amara Silva",
},
"subject": body.subject,
"content": [{
"type": "text/plain",
"value": body.message,
}],
}),
});
let respContent = "";
// only send the mail on "POST", to avoid spiders, etc.
if( request.method == "POST" ) {
const formData = await request.formData();
for (const entry of formData.entries()) {
body[entry[0]] = entry[1];
}
//fls = JSON.parse(JSON.stringify(body));
const resp = await fetch(send_request);
const respText = await resp.text();
respContent = resp.status + " " + resp.statusText + "nn" + respText + body.name;
}
let htmlContent = "<html><head></head><body><pre>" +
'</pre><p>Click to send message: <form method="post">Name: <input type="text" name="name"/><br>Email: <input type="text" name="email"/><br>Sub: <input type="text" name="subject"/><br>Msg: <input type="text" name="message"/><br><input type="submit" value="Send"/></form></p>' +
"<pre>" + respContent + "</pre>" +
"</body></html>";
return new Response(htmlContent, {
headers: { "content-type": "text/html" },
})
}
The problem is that it working if I hardcode the values but if supply them dynamically from the JSON variable then it’s not working. I am keep getting 404 error with “”Content value must be at least one character in length.”” in the response. I am a beginner in JS…how should I fix this?