最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - MERN Application "ERR_CONNECTION_REFUSED" error - Stack Overflow

programmeradmin2浏览0评论

Problem Description: I'm working on a full-stack application using React (frontend), Express.js (backend), and MongoDB. While trying to send a POST request from my React frontend to the Express backend, I encounter the following error: ERR_CONNECTION_REFUSED.

The error i get

//Register.jsx (Frontend)
import React, {Component, 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 {
    // Kullanıcıyı veritabanına kaydediyoruz
    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'

I've already tried the following steps:

I checked my routes and used Postman to verify it. Verified that the backend is running on http://localhost:5000. Added the cors middleware to the backend. Checked the fetch request configuration in the frontend. However, the issue persists, and the backend doesn't seem to receive the request.

Problem Description: I'm working on a full-stack application using React (frontend), Express.js (backend), and MongoDB. While trying to send a POST request from my React frontend to the Express backend, I encounter the following error: ERR_CONNECTION_REFUSED.

The error i get

//Register.jsx (Frontend)
import React, {Component, 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 {
    // Kullanıcıyı veritabanına kaydediyoruz
    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'

I've already tried the following steps:

I checked my routes and used Postman to verify it. Verified that the backend is running on http://localhost:5000. Added the cors middleware to the backend. Checked the fetch request configuration in the frontend. However, the issue persists, and the backend doesn't seem to receive the request.

Share Improve this question asked Nov 19, 2024 at 10:52 Onur GoksuOnur Goksu 11 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0
  • In index.js dotenv.config() should be used
  • Go to your MongoDB network access and change it to access from everywhere.
  • Clear browser cache
  • Check your API keys

If error still occurred use your local MONGODB

发布评论

评论列表(0)

  1. 暂无评论