找不到错误:POST http:// localhost:8000 / api / submit

时间:2019-05-08 17:42:14

标签: reactjs express nodemailer

我在React中有一个简单的表单,它向/ api / submit提交了一个发布请求,然后我的快速服务器按照下面的代码片段处理该发布请求,但是我收到一条错误消息:http://localhost:8000/api/submit 404(未找到)。我觉得我错过了一些基本知识。任何建议深表感谢。

我的Webpack代理如下:

devServer: {
    contentBase: path.resolve('src'),
    hot: true,
    open: true,
    port: 8000,
    watchContentBase: true,
    historyApiFallback: true,
    proxy: {
      '/api': {
        target: 'http://localhost:4000',
        secure: false
      }
    }
  }

客户端(窗体):

formSubmit(e){
    e.preventDefault()

    axios.post('/api/submit', this.state.data)
    .then(() => {
        this.setState({ sent: true }, this.resetForm())
    })
    .catch(() => {
        console.log('Message not sent')
    })
}

服务器端:

app.post('/api/submit', (req, res) => {
  const data = req.body
  console.log(req.body)

  const smtpTransport = nodemailer.createTransport({
    service: 'gmail',
    port: 25,
    auth: {
      user: process.env.EMAIL,
      pass: process.env.PASS
    }
  })

  const mailOptions = {
    from: data.email,
    to: process.env.EMAIL,
    subject: 'Quote & Services',
    html: `<p>${data.name}</p>
    <p>${data.email}</p>
    <p>${data.message}</p>`
  }

  smtpTransport.sendMail(mailOptions,
    (error, res) => {
      if(error) {
        res.send(error)
      }else {
        res.send('Success')
      }
      smtpTransport.close()
    })
}) 

app.use(express.static(`${__dirname}/dist`))

app.get('/*', (req, res) => res.sendFile(`${__dirname}/dist/index.html`))

app.listen(process.env.PORT, () => console.log(`Express is serving the dist folder on port ${process.env.PORT}`))

1 个答案:

答案 0 :(得分:0)

res回调中将覆盖smtpTransport.sendMail变量,您应使用不同的名称