我想使用客户端路由渲染我的 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/