I’m currently trying to learn so i’m following a tutorial to create a blog application using
mysql, express and react.
I’m trying to implement an authentification system and I’m stuck on the register part.
It seems that I have a problem with my front because when i’m trying to fill my register form, I get the following error : POST http://localhost:3000/api/auth/register 404 (Not Found) Register.jsx:24
Here’s my code:
*On the server side: *
Index.js
import express from "express";
import postRoutes from "./routes/posts.js"
import userRoutes from "./routes/users.js"
import authRoutes from "./routes/auth.js"
import cookieParser from "cookie-parser";
import cors from "cors";
const app = express();
app.use(
cors({
origin: "http://localhost:3000",
credentials: true
})
);
app.use(express.json());
app.use(cookieParser());
app.use("/api/auth", authRoutes);
app.use("/api/users", userRoutes);
app.use("/api/posts", postRoutes);
app.listen(8800,()=>{
console.log('Connected');
})
controllers/auth.js
import { db } from "../db.js";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
export const register = (req, res) => {
//CHECK EXISTING USER
const q = "SELECT * FROM users WHERE email = ? OR username = ?";
db.query(q, [req.body.email, req.body.username], (err, data) => {
if (err) return res.status(500).json(err);
if (data.length) return res.status(409).json("User already exists!");
//Hash the password and create a user
// const salt = bcrypt.genSaltSync(10);
// const hash = bcrypt.hashSync(req.body.password, salt);
const pwd = bcrypt.hash(req.body.password, 10, function(err, hash) {
// Store hash in your password DB.
});
const q = "INSERT INTO users(`username`,`email`,`password`) VALUES (?)";
const values = [req.body.username, req.body.email, pwd];
db.query(q, [values], (err, data) => {
if (err) return res.status(500).json(err);
return res.status(200).json("User has been created.");
});
});
};
routes/auth.js:
import express from "express";
import { register, login, logout } from "../controllers/auth.js";
const router = express.Router();
router.post("/register", register);
router.post("/login", login);
router.post("/logout", logout);
export default router;
in the package.json i added:
"proxy": "http://localhost:8800/api/"
and finally, client side:
import React from "react";
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";
const Register = () => {
const [inputs, setInputs] = useState({
username: "",
email: "",
password: "",
});
const [err, setError] = useState(null);
const navigate = useNavigate();
const handleChange = (e) => {
setInputs((prev) => ({ ...prev, [e.target.name]: e.target.value }));
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post("/auth/register", inputs);
navigate("/login");
} catch (err) {
setError(err.response.data);
}
};
return (
<div className="auth">
<h1>Register</h1>
<form>
<input
required
type="text"
placeholder="username"
name="username"
onChange={handleChange}
/>
<input
required
type="email"
placeholder="email"
name="email"
onChange={handleChange}
/>
<input
required
type="password"
placeholder="password"
name="password"
onChange={handleChange}
/>
<button onClick={handleSubmit}>Register</button>
{err && <p>{err}</p>}
<span>
Do you have an account? <Link to="/login">Login</Link>
</span>
</form>
</div>
);
};
export default Register;
Here is what I tried already:
- I tried without the proxy, to create a const with my whole URl and then use it in my axios.post(url, inputs).
- Added cors
- tried to add console.logs in my register function or my handleSubmit function but it wasn’t successful
2
Answers
Do it
You can set default base url for axios.
And call api using this axiosInstance.