React-Router 和 Express-Router 冲突

React-Router and Express-Router conflict

我在点击 api post 从 react-app 到 express 服务器的请求时遇到了一个问题。

路由冲突。

发送 post 请求时,在浏览器网络选项卡中 posting 成功但请求继续加载。可能是什么原因?

应用程序路由 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>
);

应用程序客户端操作方法:

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 });
    }
 }
}

快递服务器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}`);
});

服务器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;

您应该防止在 React 中提交表单时导致页面重新加载的默认操作。尝试 e.preventDefault()