Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What did I do wrong when I push database registers to Json-server to users.json. I have 404 not found

I am new to ReactJs coding, I have watched some videos about fake JSON-Server, but I don’t know how to post all data from register.js to my "users.json" through "server.js".

What I do is I have an edit "package.json" "script": "auth": "node server.js" and npm i json-server, npm i json-server jsonwebtoken body-parser –save-dew and npm run auth to run server.js
I learn this on youtube…

Here is my source code. Someone can fix my wrong "post", Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

users.json

{
    "users": [
      { 
        "id": 1 
        "username":"admin",
        "email": "123@gmail.com",
        "phone": "01234",
        "pass": "admin1234",
        "gender":"female",
        "role":"shop"
      }
    ]
  }

server.js

const fs = require("fs"); 
const bodyParser = require("body-parser");
const jsonServer = require("json-server");
const jwt = require("jsonwebtoken");


const server = jsonServer.create();
const userdb = JSON.parse(fs.readFileSync("./database/users.json", "utf-8"));
server.use(bodyParser.urlencoded({extended: true}));
server.use(bodyParser.json());
server.use(jsonServer.defaults());

const SECRET_KEY = "85423112"; //*random key to see access-token
const expiresIn = "1h";

function createToken(payload) {
    return jwt.sign(payload, SECRET_KEY, {expiresIn});
}
function isLoginAuthenticated({username, password}) {
    return (
        userdb.users.findIndex((user) => user.username === username && user.pass === password) !== -1 
    ); ư
}
function isSignupAuthenticated({username}) {
    return (
        userdb.users.findIndex((user) => user.username === username ) !== -1);}
   
server.post("api/auth/register", (req,res)=>{
    const {username,email,phone,password, gender,role} = req.body;
    if(isSignupAuthenticated({username})){
        const status = 401;
        const message = "Username already taken";
        res.status(status).json({status,message}) //*taken err will appeare in web console
        return;
    }

    fs.readFile(".database/users.json", (err, data) => {
        if(err){
             const status = 401;
             const message = "err"; 
             res.status(status).json({status,message}) //*err when read file in system will appeare in web console
             return;
        }
         data = JSON.parser(data.toString()); 
        let last_item_id = data.users[data.user.length - 1].id;

        data.users.push({id: last_item_id +1, username:username,email:email,phone: phone, pass:password,  gender:gender, role:role });
        let writeData = fs.writeFile("./database/users.json", JSON.stringify(data), (err, result)=>{
            if (err) {
                const status = 401;
                const message = "err"; 
                res.status(status).json({status,message}) 
                return;
            }
        });
    });
    const access_token = createToken({username,password});
    res.status(200).json({access_token}); //* set status to be OKKKKK when create account success =)))
});

   server.post("/api/auth/login", (req,res)=>{
    const {username,password} = req.body;
    if(!isLoginAuthenticated({username,password})){
        const status = 401;
        const message = "Incorrect Username or Password";
        res.status(status).json({status,message}) //*wrong will appeare in web console
        return;
   }
   const access_token = createToken({username,password});
   res.status(200).json({access_token}); //* set status to be OKKK when login ok =)))
 });
 server.listen(5001, ()=>{
     console.log("running json api server");
 });

Register.js

import React, {useState} from 'react'
import '../styles/Signup.css'
import axiox from "axios";
import {useHistory, Link} from 'react-router-dom'
import VisibilityIcon from '@mui/icons-material/Visibility'
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff'
function Register() {
  const [username,setUsername]= useState("");
  const [password,setPassword]= useState("");
  const [email,setEmail]= useState("");
  const [phone,setPhone]= useState("");
  const [gender,setGender]= useState("");
  const [role,setRole]= useState("");
  const [error, setError]= useState("");  
  let history = useHistory();


  const [showPass,setshowPass]= useState(false);    
  const [showconfirmPass,setshowconfirmPass]= useState(false);    

const register = (e) => {
  e.preventDefault();
  axiox.post("http://localhost:5001/api/auth/register", 
  {username,
  email,
  phone,
  password,
  gender,
  role,

    }).then((response)=> {
      console.log("response", response)
      localStorage.setItem("login", JSON.stringify({
     userLogin: true,
      token: response.data.access_token,
      }));
    setError("");
    setUsername("");
    setEmail("");
    setPhone("");
    setPassword("");
    setGender();
    setRole();
     history.push("/login");
    }).catch(error =>setError(error.response.data.message));
  };
    return (
       <div>
         <div id="getstarted">Get started</div>
<div id="intro"><span>Sign up</span> to our website and start to explore your unique style today !</div>
<div class="center">
      <form onSubmit={register}>
  
        <div class="txt_field">
          <input type="text" required
           value={username} 
           onChange={(e)=> setUsername(e.target.value)}/>
          <span></span>
          <label>Username</label>
        </div>
        
          <div class="txt_field">
          <input type="text" required
          value={email} 
          onChange={(e)=> setEmail(e.target.value)}/>
          <span></span>
          <label>Email</label>
        </div>
          
          <div class="txt_field">
          <input type="text" required
          value={phone} 
          onChange={(e)=> setPhone(e.target.value)}/>
          <span></span>
          <label>Phone number</label>
        </div>
          
        <div class="txt_field">
          <input type={showPass ?"text":"password" }required
          value={password} 
          onChange={(e)=> setPassword(e.target.value)}/>
          <span></span>
          <label>Password</label>
        </div>
        <div class="password1" onClick={()=>{if(showPass == true){setshowPass(false)}else {setshowPass(true)}}}> 
                 {showPass ? <VisibilityIcon/> : <VisibilityOffIcon/>}
        </div>
          <div class="txtfield_1">
          <input type={showconfirmPass ?"text":"password" } required/>
          <span></span>
          <label>Confirm Password</label>  
        </div>
        <div class="confirm"  onClick={()=>{if(showconfirmPass == true){setshowconfirmPass(false)}else {setshowconfirmPass(true)}}}> 
                 {showconfirmPass ? <VisibilityIcon/> : <VisibilityOffIcon/>}

          {error && <p2 style={{
          color:"red",
           position:"absolute",
           top:"580px", width:"500px", left:"15vw"
           }}>{error}</p2>}

        </div>
          <div id="general">
          <div class="signup_link">
          Already have an account? <Link to="/login">Sign in</Link>
        </div>
        <input type="submit" value="Learn More"/>
        </div>
      </form>
    </div>
    
    <div id="rightside">
    <div id="sex">Sex</div>
    <div id="button">

        <input type="radio" name="gender" value={gender =="male"} onChange={(e)=> setGender(e.target.value)}/>
        <label for="male"></label>
        <span>Male</span>
        <input type="radio" name="gender" value={gender =="female"} onChange={(e)=> setGender(e.target.value)}/>
        <label for="female"></label>
        <span>Female</span>
    </div>
    <div class="rect1">
      <button class="button" type="button" value={role == "shop"} onChange={(e)=> setRole(e.target.value)}><img src={process.env.PUBLIC_URL + `/Images/shop 1.png`} /></button>
    </div>
    <div class="rect2">
      <button class="button" type="button" value={ role == "customer"} onChange={(e)=> setRole(e.target.value)}> <img src={process.env.PUBLIC_URL + `/Images/take-away.png`} /></button>
      </div>
      </div>
      </div>
    );
    }
export default Register

>Solution :

You should change your route from server.post("api/auth/register", (req,res)=>{ to server.post("/api/auth/register", (req,res)=>{ in server.js file

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading