1

I am trying to create an contact page using ReactJs NodeJs express and nodemail. I am not getting any error. But it's not working. The post request is not working so i guess there's something wrong with the axios function but it could be anywhere else too so.Is the error in the backend part or the frontend part How do i fix it?

Post Log saying

Proxy error: Could not proxy request /api/forma from localhost:3000 to localhost:3001 (ECONNRESET)

Client side

import React,{useState} from 'react'
import axios from 'axios';


const Form = () => {
    const [name,setName] = useState("");
    const [email,setEmail] = useState("");
    const [message,setMessage] = useState("");
    const [sent,setSent] = useState(false);

    const formSubmit=(e)=> {
        e.preventDefault();

        let data = {
            name:name,
            email:email,
            message:message
        }

        axios.post('/api/forma',data)
        .then(res => {
            setSent(true);
        },resetForm())
        .catch(() => {
            console.log("message not sent");
        })

    }

    const resetForm = () => {
        setName("");
        setEmail("");
        setMessage("");
    
        setTimeout(()=> {
            setSent(false);
        },3000)  
    }

    

    return (
        <div className="container">
            <form onSubmit={formSubmit}>
                <div className="single">
                    <label>Name</label>
                    <input type="text" name="name" className="name" placeholder="Enter your name" 
                    value={name}
                    onChange={e => setName(e.target.value)}
                    />
                </div>
                <div className="single">
                    <label>Email</label>
                    <input type="text" name="email" className="email" placeholder="Enter your email"
                    value={email}
                    onChange={e => setEmail(e.target.value)}/>
                </div>

                <div className="textarea">
                    <label>Message</label>
                    <textarea name="message" id="" cols ="30" rows="5" placeholder="Enter your message here"
                    value={message}
                    onChange={e => setMessage(e.target.value)}></textarea>
                </div>

                <div className={sent?'msg msgAppear':'msg'}>
                    Message has been sent
                </div>

                <div>
                    <button type="submit">submit</button>
                </div>
            </form>
        </div>
    )
}

export default Form

Server side

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer')
const cors = require('cors')

const app = express();

app.use(bodyParser.json);
app.use(bodyParser.urlencoded({extended:true}));
app.use(cors());

app.get('/',()=>{
    resizeBy.send("Welcome")
});

app.post('/api/forma',(req,res) => {
    let data = req.body
    let smtptransport = nodemailer.createTransport({
        service:'Gmail',
        port:465,
        auth:{
            user:'[email protected]',
            pass: "secreate"
        }
    });

    let  mailOptions = {
        from:data.email,
        to:'[email protected]',
        subject:`Message from ${data.name}`,
        html:`
        <h3>Informations<h3>
        <ul>
        <li>Name: ${data.name}</li>
        <li>Name: ${data.email}</li>
        </ul>

        <h3>Message<h3>
        <p>${data.message}</p>
        `

    }


    smtptransport.sendMail(mailOptions,(error,response) => {
        if(error){
            res.send(error)
        }
        else{
            res.send('Success')
        }
    })

    smtptransport.close();
})

    const PORT = process.env.PORT || 3001;

    app.listen(PORT,() => {
        console.log(`Server starting at port ${PORT}`);
    })
11
  • Can you share network logs from the dev tool? what you are getting for post request. As well as add quotes around the password while login in to the nodeMailer. Commented Dec 31, 2020 at 7:35
  • Yeah there's a POST request after i submitted the form and yes i added the quotes around the password too. Commented Dec 31, 2020 at 7:43
  • network log of POST /api/forma ? Commented Dec 31, 2020 at 8:06
  • 1
    Just a heads-up if your backend is running on your local machine, it will not be able to send out the emails unless configured to. You need to run on a live server Commented Dec 31, 2020 at 10:26
  • 1
    can you make sure on which ports your client and backend service is running. one more thing can you add the backend URL directly in the Axios call. meaning instead of axios.post('/api/forma',data) do Axios.post('/localhost:3001/api/forma',data) Commented Dec 31, 2020 at 15:25

1 Answer 1

1

One way to solve this using gmail is creating a transporter.

Here is the working code:

mail.service.js

const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: '<myuser>@gmail.com',
        pass: '<mypassword>'
    },
    logger: false, // log to console
    debug: false // include SMTP traffic in the logs
});

exports.sendEmail = function(req, res) {
    const mailOptions = {
        from: '<myuser>@gmail.com',
        subject: 'My custom title ',
        text: 'Mensagem de: ' + req.body.nome + ', email: [' + req.body.email + '] ' + req.body.mensagem,
        to: req.body.email
    }
    transporter.sendMail(mailOptions).then((trans) => {
        res.status(200);
        res.json(trans);
        res.end();
    }).catch((error) => {
        res.status(500);
        res.json(error);
        res.end();
    });
}

Here is my router for sendemail action:

const router = require('express').Router();
const emailService = require('../services/mail.service.js');

router.post('/sendmail', emailService.sendEmail);

module.exports = router;

If you are in some situation of 403 errors you might need to do this configurations steps provided by nodemailer (this configuration is in gmail account) .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.