Not able to send an axios post to a node js server - net::ERR_CONNECTION_REFUSED on localhost

I'm trying to send a form from a react/node/axios website on my localhost:3000 and a node/nodemailer server running on localhost: 4000, when a submit the form/axios.post it take some seconds then i receive this error on clg:

Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError 
(xhr.js:84) xhr.js:177 POST http://localhost:4000/send_mail net::ERR_CONNECTION_REFUSED

I have tried a lot of things on code and also on my machine like, disabling firewall/protections... nothing worked.

This is the react component i'm using:

import React from 'react';
import { Link } from 'react-router-dom';
import ReCAPTCHA from 'react-google-recaptcha';
import axios from 'axios';

import './style.css';

const ContactForms = () => {
    const [isWork, setIsWork] = React.useState(false);

    const [name, setName] = React.useState('');
    const [telephone, setTelephone] = React.useState('');
    const [email, setEmail] = React.useState('');
    const [file, setFile] = React.useState();
    const [message, setMessage] = React.useState('');

    const [sent, setSent] = React.useState(false);
    const [msg, setMsg] = React.useState('');
    const recaptchaRef = React.createRef();

    console.log(sent);
    console.log(name);

    const handleSand = async (e) => {
        e.preventDefault();

        const token = await recaptchaRef.current.executeAsync();

        // const formData = new FormData();
        // formData.append('name', name);
        // formData.append('telephone', telephone);
        // formData.append('email', email);
        // formData.append('token', token);
        // formData.append('file', file);
        // formData.append('message', message);

        axios
            .post('http://localhost:4000/send_mail', {
                name,
                telephone,
                email,
                token,
                file,
            })
            .then((r) => {
                setSent(true);
                setMsg(r.data.message);
            })
            .catch((e) => {
                console.log(e);
            });
    };

    console.log(file);

    if (sent) return <div>{msg}</div>;
    return (
        <>
            {!sent ? (
                <section className="faleConosco" id="forms">
                    <div className="faleConosco__background"></div>
                    <div className="faleConosco__formulario">
                        <div className="faleConosco__buttons">
                            <button
                                className="button--amarelo amarelo"
                                onClick={() => setIsWork(false)}
                            >
                                Fale conosco
                            </button>
                        </div>
                        <div className="faleConosco__info">
                            <h2 className="faleConosco__title title--style">
                                Faça parte do nosso time
                            </h2>
                            <span className="faleConosco__subtitle">
                                E transforme a gestão de telecom com a gente
                            </span>

                            <form className="formularioContato" onSubmit={handleSand}>
                                <input
                                    type="text"
                                    placeholder="Nome completo"
                                    value={name}
                                    onChange={(e) => setName(e.target.value)}
                                    required
                                />
                                <button type="submit" className="button--azul">
                                    Enviar
                                </button>

                                <label>
                                    <input type="checkbox" required />
                                    Eu li, estou ciente das condições de tratamento dos meus dados
                                    pessoais e dou meu consentimento, quando aplicável, conforme
                                    descrito nesta política de privacidade
                                </label>

                                <ReCAPTCHA
                                    sitekey="6Lf3EpAaAAAAAOaWFeNFGhqaQk0Fab4gMfDclxx0"
                                    size="invisible"
                                    ref={recaptchaRef}
                                />
                            </form>
                        </div>
                    </div>
                </section>
            ) : (
                <section className="faleConosco" id="forms">
                    <div className="faleConosco__background"></div>
                    <div className="faleConosco__formulario">
                        <h1>enviado</h1>
                    </div>
                </section>
            )}
        </>
    );
};

export default ContactForms;

This is my server code:

const express = require('express');
const app = express();

require('dotenv').config();

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

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

app.use(cors());

app.post('/send_mail', cors(), async (req, res) => {
    let { text } = req.body;
    const transport = nodemailer.createTransport({
        service: process.env.MAIL_SERVICE,
        auth: {
            user: process.env.MAIL_USER,
            pass: process.env.MAIL_PASS,
        },
        tls: {
            rejectUnauthorized: false,
        },
    });

    await transport.sendMail({
        from: `Leads Tel&Com <${process.env.MAIL_USER}>`,
        to: `${process.env.MAIL_USER}`,
        subject: 'teste',
        text: 'teste',
    });
});

app.listen(
    (process.env.PORT || 4000,
    () => {
        console.log('Server is listening on port 4000');
    })
);

Upvotes: 2

Views: 4697

Answers (2)

Vengleab SO
Vengleab SO

Reputation: 814

I think your backend app is not running, you have extra bracket app.listen((....)) with app.listen

old code

app.listen(
    (process.env.PORT || 4000,
    () => {
        console.log('Server is listening on port 4000');
    })
);

new code

app.listen(process.env.PORT || 4000, () => {
    console.log('Server is listening on port 4000');
});

Upvotes: 1

Lavish Kumar
Lavish Kumar

Reputation: 136

I noticed that you are using cors() as middleware then why are you sending cors() again in your post route in your backend. Any request to your backend will eventually go through app.use(cors()) no need to send cors again in the post route.

Also check your frontend you most probably have a cors error. Probably because of the above mentioned problem.

Upvotes: 0

Related Questions