0

I am stuck on one problem while hitting api post request from react-app to express server.

Route confliction arises.

While sending post request, in browser network tab enter image description hereposting is successful but requesting goes on loading. what might be the causes?

app routing class, App.jsx

return (
<div className="item-main-container">
  <Header data={resumeData.main} />
  <Switch>
    <Route exact path='/' render={ () => <About data={resumeData.main}/> }/>
    <Route path='/contact' render={ () => <Contact data={resumeData.main}/> }/>
  </Switch>
  <Footer data={resumeData.main} />
</div>
);

app client action method:

export const submitForm = (data: resumeDataType["formData"]) => {
return async (dispatch: any) => {
    try{
        const response = await axios.post('/api/sendMail', data);
        dispatch({ type: EMAIL_SENT_SUCCESS, payload: response });
    } catch {
        dispatch({ type: EMAIL_SENT_ERROR });
    }
 }
}

express server index.js

const express = require('express');
const app = express();
const route = require("./route");
const cors = require("cors");

const port = process.env.PORT || 3001;
app.use(cors());
app.use("/api", route);

app.post("*", (req, res, next) => {
  console.log('post all request');
});

app.listen(port,  () => {
  console.log( `Server Running at ${port}`);
});

server route.js

const express = require('express');
const mailer = require("nodemailer");

const router = express.Router();
router.use(express.urlencoded({ extended: true }));
router.use(express.json());

router.post("/sendMail", (req, res) => {
const data = req.body;

const smtpTransport = mailer.createTransport({
    service: "Gmail",
    port: 587,
    auth: {
        user: "gmail-username",
        pass: "gmail-password"
    }
});

var mail = {
    from: data.contactEmail,
    to: "sushilpearl13@gmail.com",
    subject: data.contactSubject,
    html: `<p>${data.contactName}</p>
          <p>${data.contactEmail}</p>
          <p>${data.contactMessage}</p>`
};

smtpTransport.sendMail(mail, function(error, response) {
    if(error) {
        console.log(error)
        res.send(error);
    } else {
        console.log( "email sent successfully");
        res.send('Success');
    }
  });
  smtpTransport.close();
 });

 module.exports = router;
Chiranjhivi Ghimire
  • 1,739
  • 1
  • 19
  • 21

1 Answers1

1

You should prevent the default action on submitting a form in react which is causing the page reloading. Try e.preventDefault()

Hem
  • 122
  • 11