400错误的请求Axios React sendmail

时间:2019-08-14 15:45:00

标签: reactjs request axios sendmail

我有错误,如何解决 我正在尝试从页面login.js中发布信息,但是当我发出请求时,错误返回400错误请求。 我的函数从存档服务器中发送邮件。js

我正在使用axios发出发布请求。

我已正确配置server.js,因为在控制台中运行节点server.js时,邮件已正确发送。

这是mi页面login.js

sendEmail = async (e) => {
this.state = {
  user: 'mail@gmail.com',
  message: 'this a message from page login.js',
}

const { user, message } = this.state

try {

  const params = new URLSearchParams();
  params.append('user', user);
  params.append('message', message);

  const response = await axios.post(
    '/sendmail',
    params,
    {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  console.log(response.data);
  if (response.data === 'recovery email sent') {
    this.setState({
      showError: false,
      messageFromServer: 'recovery email sent',
      showNullError: false,
    });
  }
} catch (error) {
  console.error(error.response.data);
  if (error.response.data === 'email not in db') {
    this.setState({
      showError: true,
      messageFromServer: '',
      showNullError: false,
    });
  }
}

};

在我的server.js中

    const express = require('express');
    const bodyParser = require('body-parser');
require('dotenv').config();
const nodemailer = require("nodemailer");
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/sendmail', (req, res) => {
  console.log(req)
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: process.env.EMAIL,
    pass: process.env.PASSWORD
  }
});

const mailOptions = {
  from: process.env.EMAIL, // sender address
  to: req.body.user, // list of receivers
  subject: "Hello  ✔", // Subject line
  text: req.body.message, // plain text body
  html: "<b>Hello world?</b>" // html body
}


transporter.sendMail(mailOptions, function (error, response) {
  if (error) {
      console.log(error);
  }
  else {
      console.log("mail sent");
      console.log(response);
  }
});

});

const PORT = process.env.PORT || 3001;

app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}!`);
})

但返回错误 Status Code: 400 Bad Request

0 个答案:

没有答案