You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React对接Node.js使用Nodemailer时报Network Error错误如何解决

问题修复方案

根因说明

你遇到的网络错误由服务端代码的3个问题导致:

  • 端口监听语法错误:app.listen 参数多套了一层括号,导致服务未正确绑定4000端口,前端请求找不到对应服务
  • 接口无返回响应:/send_mail 接口逻辑执行完后没有给前端返回任何响应,请求会因超时报错
  • 缺少异常捕获:邮件发送过程中如果出现配置错误、授权失败等问题,接口会直接抛出未捕获异常,导致前端请求异常

修复后的完整服务端代码

const express = require("express");
const app = express();
require("dotenv").config();

const bodyParser = require("body-parser");
const cors = require("cors");
const nodemailer = require("nodemailer");

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

app.use(cors());

app.post("/send_mail", cors(), async (req, res) => {
  try {
    let { text } = req.body;
    const transport = nodemailer.createTransport({
      host: process.env.MAIL_HOST,
      port: process.env.MAIL_PORT,
      auth: {
        user: process.env.MAIL_USER,
        pass: process.env.MAIL_PASS,
      },
    });

    await transport.sendMail({
      from: process.env.MAIL_FROM,
      to: "test@test.com",
      subject: "test email",
      html: `<div className="email" style="
          border: 1px solid black;
          padding: 20px;
          font-family: sans-serif;
          line-height: 2;
          font-size: 20px; 
          ">
          <h2>Here is your email!</h2>
          <p>${text}</p>
      
          <p>All the best, Ala</p>
           </div>
      `,
    });
    // 新增成功响应
    res.json({
      status: 'success',
      message: '邮件发送成功'
    })
  } catch (err) {
    // 新增错误捕获和返回
    res.status(500).json({
      status: 'fail',
      message: err.message
    })
  }
});

// 修正端口监听的语法错误,去掉多余括号
app.listen(process.env.PORT || 4000,
  () => {
    console.log("Server is listening on port 4000");
  }
);

额外检查项

修复代码后请确认以下配置正常:

  • .env 文件中的邮件服务配置(HOST、PORT、账号、授权码)正确
  • 前端请求的地址是 http://localhost:4000/send_mail,端口和服务端监听端口一致
  • 如果你使用的是 Gmail、QQ 邮箱等公共邮件服务,需要确认已开启SMTP服务、使用授权码而非账号密码登录

内容的提问来源于stack exchange,提问作者Alaa Strong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 18:27:05