I tried other solutions but still no luck. I'm adding a simple contact form on my React/Node app using Nodemailer. I'm using Heroku to deploy the app and currently testing on my local server. Although a message is delivered to the assigned mailbox, I keep getting errors net::ERR_EMPTY_RESPONSE
and TypeError: Failed to fetch
after the Node.js core's 2 minute timeout.
I have tried 1) both axios and fetch request on the client side and 2) adding CORS headers in the server file but the same results.
app.use(function(req, res, next) {
console.log('request', req.url, req.body, req.method);
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Request-Method: GET,PUT,POST,DELETE,OPTIONS")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-token");
if(req.method === 'OPTIONS') {
res.end();
} else {
next();
}
});
This is the submit handler method from the client side:
handleFormSubmit(e){
e.preventDefault();
console.log(this.state);
console.log('submit clicked');
const data = {
"fname": this.state.fname,
"lname": this.state.lname,
"email": this.state.email,
"message": this.state.message
}
fetch("http://localhost:3000/api/form", {
method: "POST",
headers: {"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify(data)
})
.then((res) => {return res.json()})
.then(res => {
if(res.ok){
console.log("request sucess");
return res.json();
} else {
console.log("request fail");
throw new Error("something went wrong..");
}
}).catch(err => {
console.log(err);
console.log("error happed");
})
I followed the Nodemailer tutorial and the routing is set correctly. The message arrives on the mailbox. I expect the output to return success but keep catching the error and I don't know what I'm doing wrong. I really appreciate for any advice.