MERN全栈应用POST请求出现ERR_CONNECTION_REFUSED问题求助
问题描述
我正在开发基于React(前端)、Express.js(后端)和MongoDB的全栈应用,在从React前端向Express后端发送POST注册请求时,遇到了ERR_CONNECTION_REFUSED错误。
相关代码
Register.jsx(前端)
import React, { useState } from 'react' import styled from "styled-components" import {Link} from "react-router-dom" import "../css/register.css" import axios from "axios"; const Register = () => { const [username,setUserName] = useState(""); const [email,setEmail] = useState(""); const [password,setPassword] = useState(""); const [passwordagain,setPasswordAgain] = useState(""); const [errorMessage, setErrorMessage] = useState(""); const handleSubmit = async (event) => { event.preventDefault(); if (password === passwordagain) { const userData = { username, email, password }; console.log("We want post:", userData); try { const response = await fetch('http://localhost:5000/auth/register', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(userData), }); const data = await response.json(); // JSON Data if (response.ok) { console.log("Register Success:", data); } else { console.log("Register Unsuccesfull:", data); setErrorMessage("Please Try Again."); } } catch (error) { console.error("Error:", error.message); setErrorMessage("Register Unsuccesfull,Please Try Again."); } } else { setErrorMessage("passwords do not match"); } }; return ( <div> <div className="formcontainer"> <form className="form" onSubmit={(event)=>(handleSubmit(event))}> <input type="text" value={username} placeholder="Enter your username" name="username" className="input" onChange={(e) => setUserName(e.target.value)} /> <input type="email" value={email} placeholder="Enter your email" name="email" className="input" onChange={(e) => setEmail(e.target.value)} /> <input type="password" value={password} placeholder="Enter password" name="password" className="input" onChange={(e) => setPassword(e.target.value)} /> <input type="password" value={passwordagain} placeholder="Enter password again" name="passwordagain" className="input" onChange={(e) => setPasswordAgain(e.target.value)} /> <button type="submit">Register</button> </form> {errorMessage && <p style={{ color: "red" }}>{errorMessage}</p>} </div> </div> ) } export default Register
index.js(后端)
const express = require("express"); const cors = require("cors"); const mongoose = require("mongoose"); const dotenv = require("dotenv"); const authRoutes = require("./routes/authRoutes"); dotenv.config(); const app = express(); // Middleware app.use(cors({ origin: "http://localhost:3000", // Frontend methods: "GET,POST,PUT,DELETE", credentials: true, })); app.use(express.json()); // JSON app.use(express.urlencoded({ extended: true })); // URL-encoded mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => console.log("MongoDB Connected.")) .catch(err => console.log("MongoDB Connection Error:", err)); app.use("/auth", authRoutes); const PORT = 5000; app.listen(PORT, () => { console.log(`Server is running. Port: ${PORT}`); });
authRoutes.js(后端)
const express = require("express"); const router = express.Router(); const authPost = require("../controllers/authControllers"); router.post("/register", authPost); module.exports = router;
authController.js(后端)
// authController.js const Auth = require("../models/authModel"); // Import Model const authPost = async (req, res) => { const { username, email, password } = req.body; console.log("Request Data In Server:", req.body); // Logging Request const newUser = new Auth({ username, email, password, }); try { // 将用户保存到数据库 const savedUser = await newUser.save(); console.log("Yeni kullanıcı kaydedildi:", savedUser); // Detailed log res.status(201).send("Kayıt başarılı"); } catch (error) { console.error("Veritabanı hatası:", error); // Error Message res.status(500).send("Kayıt başarısız: " + error.message); } }; module.exports = authPost;
authModel.js(后端)
const mongoose= require("mongoose"); const authSchema = mongoose.Schema({ username: { type: String, required: true }, email: { type: String, required: true }, password: { type: String, required: true } }); const Auth = mongoose.model("Auth", authSchema); // Collection name 'User'
已尝试的解决方案
- 检查路由并通过Postman验证
- 确认后端运行在http://localhost:5000
- 在后端添加CORS中间件
- 检查前端fetch请求配置
排查建议
- 确认后端服务正常运行:查看后端启动终端,确认是否输出
Server is running. Port: 5000,若没有启动成功,检查启动日志(比如MongoDB连接失败、代码语法错误等),修复后重启服务。 - 检查端口占用情况:
- Windows系统执行命令:
netstat -ano | findstr :5000 - Mac/Linux系统执行命令:
lsof -i :5000
若5000端口被其他进程占用,修改后端PORT为其他未被占用的端口,同时同步更新前端fetch请求的URL。
- Windows系统执行命令:
- 验证Postman直接请求:用Postman发送POST请求到
http://localhost:5000/auth/register,如果同样无法连接,说明问题出在后端服务本身,和前端无关。 - 临时调整CORS配置:将后端CORS改为
app.use(cors())(允许所有来源),测试是否能正常请求,排除CORS配置的问题,之后再恢复严格的origin设置。 - 检查防火墙/安全软件:本地防火墙或杀毒软件可能拦截本地端口请求,临时关闭后重新测试。
- 确认前端运行端口:确保前端确实在
http://localhost:3000运行,若前端端口不同,修改后端CORS的origin参数为前端实际地址。
内容的提问来源于stack exchange,提问作者Onur Goksu
相关产品推荐
相关产品推荐

