请求陷入待处理状态

问题描述 投票:0回答:1

当我尝试使用 React 和 Express 发出 POST 请求时,请求卡在请求的中间件中。对于前端部分,我使用 React 的 CRA 和 Express js 作为后端。 我不确定问题出在哪里,但任何建议都会非常有帮助。

后端

服务器.js


var express = require('express');
var app = express();
var cors = require('cors');
const corsOptions = {
  origin: '*',
  credentials: true,
  optionSuccessStatus: 200,
};

app.use(cors(corsOptions));
app.use("/contact", contact);
app.use("/offer", offer);

app.listen(3015);

index.js

var nodemailer = require('nodemailer');
var cors = require('cors');
const creds = require('../../config');
const app = express();
const corsOptions = {
  origin: '*',
  credentials: true,
  optionSuccessStatus: 200,
};

// Multiple routing
const router1 = express.Router();
const router2 = express.Router();

app.use(cors(corsOptions));
app.use(express.json());
app.use('/contact', router1);
app.use('/offer', router2);
app.set('port', 3015);

var transport = {
  host: 'kelvin.superhosting.bg',
  port: 587,
  auth: {
    user: creds.USER,
    pass: creds.PASS
  }
}
var transporter = nodemailer.createTransport(transport)
transporter.verify((error, success) => {
  if (error) {
    console.log(error);
  } else {
    console.log(success);
    // console.log('Server is ready to take messages');
  }
});

exports.contact = () => {
  router1.post('/contact', (req, res, next) => {
    // console.log('req.body', req.body);
    var name = req.body.name;
    var email = req.body.email;
    var subject = req.body.subject;
    var message = req.body.message;
    var content = `name: ${name} \n email: ${email} \n\n message: ${message} `;
    var mail = {
      from: name,
      to: '[email protected]',  // Change to email address that you want to receive messages on
      subject: subject,
      text: content
    }
    transporter.sendMail(mail, (err, data) => {
      if (err) {
        console.log('err', err)
        res.json({
          status: 'fail'
        })
      } else {
        console.log('here');
        res.json({
          status: 'success'
        })
      }
    });
    next();
  });
}

exports.offer = async () => {
  await router2.post('/offer', (req, res, next) => {
    console.log('req.body', req.body);
    var subject = "Hey this is a subject example";
    var mail = {
      to: '[email protected]',  // Change to email address that you want to receive messages on
      subject: subject,
      attachments: [
        {
          filename: `${req.body.attachments[0].filename}`,
          content: `${req.body.attachments[0].content}`,
          encoding: `${req.body.attachments[0].encoding}`,
        },
      ],
    }
    transporter.sendMail(mail, (err, data) => {
      if (err) {
        res.json({
          status: 'fail'
        })
      } else {
        res.json({
          status: 'success'
        })
      }
    });
  });
}

前端 索引.jsx

async function fetchMessage() {
    const response = await fetch(`http://localhost:3015/contact`, {
      method: "POST",
      body: JSON.stringify(values[0]),
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
    }).then(
      (response) => (response.json())
    ).then((response) => {
      if (response.status === 'success') {
        setValues([]);
        setName('');
        setEmail('');
        setSubject('');
        setMessage('');
        setCaptchaText('');
        onRefresh();
        setMessageOpen(true);
      } else if (response.status === 'fail') {
        console.log("Message failed to send.", response)
      }
    });

    return response;
  }

我还尝试了几种方法来解决这个问题。例如,在前端和后端都有/没有异步/等待,我多次重新启动服务器以及我的本地计算机。

javascript reactjs node.js express create-react-app
1个回答
0
投票

在控制器函数(

contact
offer
)中,您将
nodemailer
sendMail
与回调函数一起使用。这就是为什么你的请求被困在后端,你正在注册一个回调,然后你的代码立即移动到
next
,所以你不会向客户端发送响应。

您可以在没有回调函数的情况下使用

sendMail
,它将返回一个 Promise,等待这个 Promise 并在
try/catch
块中使用它,如果 Promise 被解决则发送成功响应,如果被拒绝则发送错误,与此类似,

try {
const info = await transporter.sendMail(mail);
console.log('here');
res.json({
    status: 'success'
})} catch (err) {
console.log('err', err)
res.json({
    status: 'fail'
})

}

© www.soinside.com 2019 - 2024. All rights reserved.