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

为何Email.js无法识别我的send-email POST路由?

React + Email.js 发送邮件出现404错误

错误信息

POST http://localhost:3000/send-email 404 (Not Found)
handleFormSubmit @ Contact.jsx:14

现有代码

server.js

import express from 'express';
import emailjs from 'emailjs-com';
import dotenv from 'dotenv';
import cors from 'cors'; // Import the cors middleware

const app = express();

// Load environment variables from .env file
dotenv.config();

app.use(express.json());

// Use the cors middleware to allow requests from all origins
app.use(cors());

app.post('/send-email', async (req, res) => {
  const { name, email, message } = req.body;

  try {
    // Send email using emailjs
    await emailjs.send(
      's*****', // Replace with your service ID. hidden from public
      '****', // Replace with your template ID hidden from public
      { 
        from_name: name,
        reply_to: email,
        message: message
      },
      process.env.EMAILJS_USER_ID // Accessing emailjs user ID from environment variable
    );

    console.log('Email sent successfully');
    res.status(200).send('Email sent successfully');
  } catch (error) {
    console.log("error:",error)
    console.error('Error sending email:', error);
    
    res.status(500).send('Failed to send email');
  }
});

const PORT =  3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Contact.jsx

import React, { useState } from "react";
import './contact.css';

const Contact = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");
  const [formError, setFormError] = useState("");

  const handleFormSubmit = async (event) => {
    event.preventDefault();

    try {
      const response = await fetch('/send-email', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name, email, message }),
      });

      if (response.ok) {
        // Email sent successfully
        console.log('Email sent successfully');
        setName('');
        setEmail('');
        setMessage('');
        setFormError('');
      } else {
        const errorMessage = await response.text();
        setFormError(errorMessage || 'Failed to send email');
      }
    } catch (error) {
      console.error('Error sending email:', error);
      setFormError('Failed to send email');
    }
  };

  return (
    <div className="contact-container" id="Contact">
      <br />
      <h2 id="contact-me" className="bib">Let's Connect!</h2>
      <br />
      <form className="contact-form" onSubmit={handleFormSubmit}>
        <div className="form-group">
          <div className="input-group">
            <input
              type="text"
              placeholder="Enter your name"
              value={name}
              onChange={(event) => setName(event.target.value)}
            />
          </div>
        </div>
        <div className="form-group">
          <div className="input-group">
            <input
              type="email"
              placeholder="Enter your email"
              value={email}
              onChange={(event) => setEmail(event.target.value)}
            />
          </div>
        </div>
        <div className="form-group">
          <div className="txtA">
            <textarea
              placeholder="Type your message here"
              value={message}
              onChange={(event) => setMessage(event.target.value)}
            />
          </div>
        </div>
        <div className="form-group">
          <button type="submit">Submit</button>
        </div>
        {formError && <p className="error-message">{formError}</p>}
      </form>
    </div>
  );
};

export default Contact;

解决办法

1. 解决端口冲突(核心问题)

React开发服务器默认占用3000端口,你的Express服务器也用了3000,导致Express服务无法正常启动,或前端请求发到了React服务器而非Express,因此出现404。

  • 修改server.js的端口为3001:
    const PORT = 3001;
    
  • 更新Contact.jsx中的fetch地址:
    const response = await fetch('http://localhost:3001/send-email', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ name, email, message }),
    });
    

2. 可选:配置React代理(避免硬编码端口)

在React项目的package.json中添加代理字段,自动转发请求到Express服务器:

"proxy": "http://localhost:3001"

之后前端可以继续用fetch('/send-email'),无需写完整地址,同时解决跨域问题。

3. 确保Express服务正常启动

  • 安装所有依赖:
    npm install express emailjs-com dotenv cors
    
  • 启动Express服务,确认控制台输出Server is running on port 3001。

4. 验证Email.js配置

检查.env文件中的EMAILJS_USER_ID是否正确,以及service ID、template ID是否与Email.js后台一致,这些配置错误会导致邮件发送失败,但不会引发404。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 04:55:42