POST http:// localhost:3000 / api / contactus 404(未找到)!!!我不明白

时间:2018-03-30 23:42:25

标签: node.js reactjs http-status-code-404 sendmail nodemailer

我对网络开发很陌生。我试图联系我们表单,当用户点击提交时,表单的内容应该发送到电子邮件。 我关注了这个YouTube视频:https://www.youtube.com/watch?v=EPnBO8HgyRU

当我尝试通过Postman发布到我的后端网址(http://localhost:3001/api/contactus)时,它确实发送了一封电子邮件,但是所有的“请求”都在电子邮件中未定义。当我从前端联系我们表单发布时,我在控制台中收到此错误:console error

我不明白我做错了什么。正如我所说,我是网络开发的新手。我正在学习,所以我不知道自己不知道什么,因此我认为这可能是一个非常简单的修复,但它超出了我的范围。

这是我的表格的前端代码我认为当我带来' axios'时出现问题。

async handleSubmit(e) {

  e.preventDefault();

  const err = this.validateForm();
  if (err) {

    if (this.state.userName.length < 2) {
      this.setState({
         userNameError: true,
      });
    }

    if (this.state.email.indexOf("@") === -1) {
      this.setState({
         emailError: true,
      });
    }


    if (this.state.subject.length < 2) {
      this.setState({
         subjectError: true,
      });
      }

     if (this.state.message.length < 2) {
       this.setState({
          messageError: true,
       });
      }
  }

  if (!err) {

  const finalForm = {
    userName: this.state.userName,
    email: this.state.email,
    subject: this.state.subject,
    message: this.state.message,
  };

  if (this.state.imagePreviewUrl) {

    let newFileName = this.state.fileName.replace(/^C:\\fakepath\\/, "");

    finalForm.attachments = [{
      filename: newFileName,
      content: this.state.imagePreviewUrl.split("base64,")[1],
      encoding: 'base64',
    }]
 }


const contactus = await axios.post('/api/contactus', {finalForm})

  this.handleFormClear(e);
  this.setState({
    formSubmit: true,
  });
}

}

此外,我希望const联系人能够接受#finalForm&#39;对于“req.body”,但由于某种原因不起作用。帮助:(

这是我的后端代码:

const express = require('express')
const bodyParser = require('body-parser')
const nodemailer = require('nodemailer')
const Form = express()

Form.use(bodyParser.json())
Form.use(bodyParser.urlencoded({ extended: false}))
Form.post('/api/contactus', (req, res) => {
  console.log(req.body);

const htmlEmail = `
<h3>Contact Details</h3>
<ul>
  <li>Name:${req.body.userName}</li>
  <li>Email:${req.body.email}</li>
  <li>Subject${req.body.subject}</li>
</ul>
<h3>Messages</h3>
<p>${req.body.message}</p>
`

const transporter = nodemailer.createTransport({
 host: 'smtp.gmail.com',
 port: 465,
 secure: true,
 auth: {
   user: 'xxxxxxxx@gmail.com',
   pass: 'xxxxxxxx',
 }


  });

   const mailOptions = {
     from: req.body.userEmail,
     to: 'xxxxxxx@gmail.com',
     subject: req.body.subject,
     text: req.body.userMessage + '\n\n' + "Send your response to: " + req.body.userEmail,
     html: htmlEmail,
     attachments: req.body.attachments && req.body.attachments
   };

   transporter.sendMail(mailOptions, (error, info) => {
     if (error) {
       console.log(error.message)
     } else {
         console.log('Message Sent: %s' , info.message)
         console.log('Message URL: %s', nodemailer.getTestMessageUrl(info))
     }
   });

})

const PORT = process.env.PORT || 3001

Form.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`)
})

请帮忙。谢谢!

新错误图片:updated error

4 个答案:

答案 0 :(得分:0)

我从您的错误中看到,您正在调用localhost:3000而不是localhost:3001

答案 1 :(得分:0)

我也遵循了本教程,并遇到了类似的问题。对我来说解决的是运行我的客户端,并在终端中使用命令npm run dev同时提供服务。假设您的projectName\package.json中有一个dev的脚本(在本教程中,该脚本大约是5:20 https://www.youtube.com/watch?v=EPnBO8HgyRU&t=542s)。如果那不能立即解决您的问题,请尝试解决终端中出现的任何其他警告或错误,然后重新运行命令。

答案 2 :(得分:0)

原始帖子最底部链接的图像中的错误显示了问题:

  

Failed to load http://localhost:3001/api/contactus: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404.

这是一个cross-origin resource sharing问题。本质上,当您尚未在Express JS服务器中启用此功能时,您正在尝试从一个域(localhost:3001)来访问另一个域(localhost:3000)的资源。

您可以在此处了解如何设置Express JS以允许CORS:

https://www.w3.org/wiki/CORS_Enabled#In_ExpressJS

答案 3 :(得分:0)

您需要使用3001端口

axios.post('http://localhost:3001/api/contactus', {finalForm})

相关问题