Home > Software engineering >  I can't post data in express server returns an error
I can't post data in express server returns an error

Time:12-07

Continuously I am trying to post data in the express server but can't do it... Showing this error on my homepage

" Error

Cannot POST /auth/login
"

I have used the database MySQL...Whenever I log in then showing this error in the browser console "Failed to load resource: the server responded with a status of 404 (Not Found)"

Login.js

import React, { useState } from "react";
import { useContext } from "react";
import { Link, useNavigate } from "react-router-dom";
import { AuthContext } from "../context/authContext";

const Login = () => {
  const [inputs, setInputs] = useState({
    username: "",
    password: "",
  });
  const [err, setError] = useState(null);
  const navigate = useNavigate();
  const {login} =useContext(AuthContext)
  
  const handleChange = (e) => {
    setInputs((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };
  console.log(inputs);
  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await login(inputs);
      navigate("/");
    } catch (err) {
      setError(err.response.data);
    }
  };
  return (
    <div className="auth">
      <h1>Login</h1>
      <form action="/" method="post">
        <input
          type="text"
          name="username"
          placeholder="User Name"
          onChange={handleChange}
        />
        <input
          type="password"
          name="password"
          password="password"
          placeholder="Password"
          onChange={handleChange}
        />
        <button onClick={handleSubmit}>Login</button>
        {err && <p>{err}</p>}
        <span>
          Don't you have any account? <Link to="/register">Register</Link>
        </span>
      </form>
    </div>
  );
};

export default Login;

Register.js

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 }));
  };
  console.log(inputs);
  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 action="/" method="post">
        <input
          required
          type="text"
          placeholder="User Name"
          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 any account? <Link to="/login">Login</Link>
        </span>
      </form>
    </div>
  );
};

export default Register;

Here is my Server side code 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.json(err);
    if (data.length) return res.status(409).json("users already exits");

    //Hash the password and create a user
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(req.body.password, salt);

    const q = "INSERT INTO users (`username`, `email`, `password`) VALUES (?)";
    const values = [req.body.username, req.body.email, hash];
    db.query(q, [values], (err, data) => {
      if (err) return res.json(err);
      return res.status(200).json("User has been created.");
    });
  });
};

export const login = (req, res) => {
  //check user
  const q = "SELECT * FROM users WHERE username = ?";
  db.query(q, [req.body.username], (err, data) => {
    if (err) return res.json(err);
    if (data.length === 0) return res.status(404).json("User Not Found!");
    //check password
    const isPasswordCorrect = bcrypt.compareSync(
      req.body.password,
      data[0].password
    );
    if (!isPasswordCorrect)
      return res.status(400).json("Wrong Username or Password");
      const token=jwt.sign({id:data[0].id}, "jwtkey");
      const {password, ...other} =data[0];
      res.cookie("access_token", token, {
        httpOnly:true
      }).status(200).json(other)
  });
};
export const logout = (req, res) => {
    res.clearCookie("access_token",{
        sameSite:"none",
        secure:true
    }).status(200).json("users has been logged out")
};

controllers/post.js

 import { db } from "../db.js";
import jwt from "jsonwebtoken";

export const getPosts = (req, res) => {
  const q = req.query.cat
    ? "SELECT * FROM posts WHERE cat=?"
    : "SELECT * FROM posts";
  db.query(q, [req.query.cat], (err, data) => {
    if (err) return res.status(500).send(err);
    return res.status(200).json(data);
  });
};
export const getPost = (req, res) => {
  const q =
    "SELECT `username`, `title`, `desc`, p.img, u.img AS userImg, `cat`, `date` FROM users u JOIN posts p ON u.id=p.uid WHERE p.id = ?";
    db.query(q,[req.params.id], (err,data) =>{
      if(err) return res.status(500).json(err)
      return res.status(200).json(data[0]);
    })
};

export const addPost = (req, res) => {
  res.json("from controller");
};
export const deletePost = (req, res) => {
  const token = req.cookies.access_token
  if(!token) return res.status(401).json("Not authenticated!");
  jwt.verify(token, "jwtkey", (err, userInfo)=>{
    if(err) return res.status(403).json("Token is not vaild!")
    const postId=req.params.id
    const q="DELETE FROM posts WHERE `id` = ? AND `uid` = ?"

    db.query(q,[postId, userInfo.id], (err, data) =>{
      if(err) return res.status(403).josn("You can delete on your post!");
      return res.json("Post has been deleted");
    })
  })
};
export const updatePost = (req, res) => {
  res.json("from controller");
};

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;

routes/posts.js

    import express from "express";
import {
  addPost,
  deletePost,
  getPost,
  getPosts,
  updatePost,
} from "../controllers/post.js";

const router = express.Router();
router.get("/", getPosts);
router.get("/:id", getPost);
router.post("/", addPost);
router.delete("/:id", deletePost);
router.put("/:id", updatePost);

export default router;

db.js

 import mysql from "mysql";

export const db= mysql.createConnection({
    host:"localhost",
    user:"root",
    password:"hideforsecuritypurpose",
    database:"blogapp"
})

express server index.js

 import cookieParser from "cookie-parser";
import express from "express";
import authRoutes from './routes/auth.js';
import postRoutes from './routes/posts.js';
import userRoutes from './routes/users.js';

const app = express();
const PORT =process.env.PORT || 5000;

app.use(express.json());
app.use(cookieParser());  
app.use("/api/auth", authRoutes);
app.use("/api/posts", postRoutes);
app.use("/api/users", userRoutes);

app.listen(PORT, () =>{
    console.log("database is connected")
})

Thanks in advance.

CodePudding user response:

Note

Cannot POST /auth/login

There's difference here -- keep in mind endpoint naming

router.post("/login",login);

and

router.post("/auth/login",login);

Furthermore you have

app.use("/api/auth", authRoutes);

Try and level out your namings for endpoints

CodePudding user response:

Installez cors ça va passer directement sans problème, npm i cors

  • Related