admin管理员组文章数量:1022580
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 badge1 Answer
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
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 badge1 Answer
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
本文标签: reactjsMERN Application quotERRCONNECTIONREFUSEDquot errorStack Overflow
版权声明:本文标题:reactjs - MERN Application "ERR_CONNECTION_REFUSED" error - Stack Overflow 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/questions/1745567146a2156519.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论