javascript - React + Express + Nodemailer : Can't render components and Nodemailer together

标签 javascript node.js reactjs express nodemailer

我想使用客户端路由渲染我的 React 应用程序,并且我想使用 Nodemailer 发送邮件。由于 Nodemailer 不能在客户端使用,我必须在 Express 服务器上实现它。 这是服务器的样子:

express.js

router.use(express.static(path.resolve(__dirname, '..', 'build')))

router.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build/index.html'))
})

router.get('/sendmail', (req, res) => {
transporter.sendMail(options, (error, info) => {
      if (error){
        console.log(error)
      }
      console.log('Message was send!')
    })
})

1) 因此,这会渲染 React 组件,但是当我路由到“/sendmail”时,会显示一个空白页面,index.html 会在没有 js 的情况下渲染,并且不会发送邮件。

2) 如果我删除第一行 router.use(express.static... 并路由到“/sendmail”,则会发送邮件,但我的应用程序不会呈现。

我还尝试了以下方法:

router.use(express.static(path.resolve(__dirname, '..', 'build')))

router.get('*', (req, res) => {
  console.log('path', req.path)

  if (req.path === '/sendmail') {
      transporter.sendMail(options, (error, info) => {
      if (error){
        console.log(error)
      }
      console.log('Message was send!')
    })
  } else {
    res.sendFile(path.resolve(__dirname, '..', 'build/index.html'))
  }
});

有什么解决办法吗?

最佳答案

只要改变express中的路由顺序,它们就会从上到下匹配:

router.use(express.static(path.resolve(__dirname, '..', 'build')))

router.get('/sendmail', (req, res) => {
// this will be processed when you send a GET for /sendmail to your express server
....
}

router.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '..', 'build/index.html'))
  // this will always match if the request is not /sendmail
})

关于javascript - React + Express + Nodemailer : Can't render components and Nodemailer together,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45368196/

相关文章:

javascript - 使用 Puppeteer 访问 React 状态

javascript - ajax成功后没有调用另一个js函数

javascript - 使用Flask和JQuery,如何在 "POST"方式中通过 "sexy"方法删除一条记录?

reactjs - json-server 主页未显示

javascript - 在 React Native 中将照片上传到 Node 服务器

mysql - 在 Node 循环中选择和插入未按预期工作

javascript - 使用 seState 和 Interval 的 React Timer 不起作用

javascript - 在 div 中显示 javascript 数组

javascript - 将 SignalR 与自托管 WCF 结合使用并通过 HTML 客户端使用集线器代理

node.js - 为什么 Node.JS Mongo.Connect() (Azure Cosmos DB) 不响应/返回任何错误?