While working on a MERN project, i am stuck on a problem while i try to get data from the register page from the form, the Axios is giving error. I am trying to send data to the database but i am stuck on this problem. i tried to refresh my app.js file but still i am unable to identify the cause.
import "./register.scss";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";
import { useState } from "react";
import apiRequest from "../../lib/apiRequest";
function Register() {
const [error, setError] = useState("")
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const username = formData.get("username");
const email = formData.get("email");
const password = formData.get("password");
try {
const res = await axios.post("http://localhost:5000/api/auth/register", {
username, email, password
})
console.log(res.data);
} catch (error) {
console.log(error);
// setError()
}
}
return (
<div className="registerPage">
<div className="formContainer">
<form onSubmit={handleSubmit}>
<h1>Create an Account</h1>
<input name="username" type="text" placeholder="Username" />
<input name="email" type="text" placeholder="Email" />
<input name="password" type="password" placeholder="Password" />
<button>Register</button>
<Link to="/login">Do you have an account?</Link>
</form>
</div>
<div className="imgContainer">
<img src="/bg.png" alt="" />
</div>
</div>
);
}
export default Register;
and this is the app.js =
import express from "express";
import cors from "cors";
import authRoute from "./routes/auth.route.js"
import postRoute from "./routes/post.route.js"
import cookieParser from "cookie-parser"
const app = express();
app.use(cors({ origin: process.env.CLIENT_URL, credentials:true }));
app.use(express.json());
app.use(cookieParser());
app.use("/api/posts", postRoute)
app.use("/api/auth", authRoute);
app.listen(process.env.PORT, ()=>{
console.log("Server is running");
})
Anyone please try to help me catch this error so that, I can finally finish this project
3
Answers
@vaibhav-bais can you tell me what error you are getting,
Give me error message, i will help
I can see in your app.js:
app.use("/api/posts", postRoute)
so you’re using
.use
and you’re trying toaxios.post
.You should try change your
app.use
toapp.post
and see if that works.The api endpoint you are trying to call from frontend I think is incomplete.
Above is the api endpoint you are calling but there is no such api endpoint in your app.js. Maybe you are intending to call
/api/auth/login