Postman测试Express邮件接口出现404 Not Found问题求助
问题:Express POST接口404排查(Resend邮件发送功能)
我在开发客户预约表单的确认邮件功能,采用Resend服务发送邮件,前端基于React,后端用Express实现了POST接口/send-email。但用Postman测试该接口时,返回404 Not Found错误,已确认路由配置和服务器运行状态正常,寻求问题排查思路。
server.js代码
const express = require('express'); const bodyParser = require('body-parser'); require('dotenv').config(); const axios = require('axios'); const app = express(); const PORT = process.env.PORT || 3003; app.use(bodyParser.json()); app.post('/send-email', async (req, res) => { const { to, subject, html } = req.body; try { const response = await axios.post('https://api.resend.com/emails', { from: process.env.RESEND_FROM_EMAIL, to, subject, html, }, { headers: { 'Authorization': `Bearer ${process.env.RESEND_API_KEY}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { res.status(200).json({ message: 'Email sent successfully' }); } else { res.status(response.status).json({ message: 'Failed to send email' }); } } catch (error) { console.error('Error sending email:', error); res.status(500).json({ message: 'Internal server error' }); } }); app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
Postman请求配置
- 请求方法:POST
- 请求地址:
http://localhost:3003/send-email - 请求体(JSON):
{ "to": "Hola@comoestas.com", "subject": "Prueba Email", "html": "<h1>Esto es un Email</h1>" }
错误返回信息
- 状态码:404 Not Found
- 返回内容:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Error</title> </head> <body> <pre>Cannot POST /send-email%0A</pre> </body> </html>
- 测试断言失败:
FAIL Response has the required fields | AssertionError: expected a{ …(7) } to have property 'content-type'
排查思路建议
- 清理请求地址的隐形字符:错误返回里的路径是
/send-email%0A,说明请求地址末尾带了换行符。手动重新输入Postman的地址栏,避免复制粘贴带来的多余字符。 - 重启服务器确保路由生效:如果修改过server.js后没重启服务器,新路由不会加载。关闭当前进程,重新运行
node server.js再测试。 - 验证基础路由连通性:临时添加一个GET测试路由:
用Postman访问app.get('/test', (req, res) => res.send('Server is reachable'));http://localhost:3003/test,确认服务器能正常响应,排除端口占用、防火墙拦截等问题。 - 检查请求头的Content-Type:确保Postman的请求头里
Content-Type设置为application/json,否则服务器无法正确解析请求体,可能导致路由匹配异常。 - 查看服务器请求日志:在
/send-email路由开头加一行日志:
测试时观察控制台,如果没有日志输出,说明请求根本没到达服务器,重点排查网络连接问题。console.log('Incoming request to /send-email'); - 确认中间件顺序:确保
app.use(bodyParser.json())在路由定义之前,避免请求体解析失败导致的路由不匹配。
内容的提问来源于stack exchange,提问作者ShailaHussein
相关产品推荐
相关产品推荐

