2017-07-28 37 views
1

我想用客戶端路由渲染我的React應用程序,並且我想用Nodemailer發送郵件。由於無法在客戶端使用Nodemailer,因此我必須在Express服務器上實現此功能。 這是服務器的樣子:React + Express + Nodemailer:無法渲染組件和Nodemailer

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)因此,這使得該反應的組分,但是當我到「/ sendmail的」空白頁路線示,該指數.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')) 
    } 
}); 

任何解決方案?

回答

0

只要改變快遞路線的順序,他們將頂部匹配底部:

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 
}) 
+0

已經嘗試過,並沒有奏效。 這就像express.static需要控制和router.get被忽略。 –