当我将数据库寄存器推送到 Json-server 到 users.json 时,我做错了什么?我有 404 未找到
What did I do wrong when I push database registers to Json-server to users.json. I have 404 not found
我是 ReactJs 编码的新手,我看过一些关于假 JSON-Server 的视频,但我不知道如何 post 来自 register.js 的所有数据到我的“users.json”到“server.js”。
我所做的是编辑 "package.json" "script": "auth": "node server.js" 和 npm i json-server, npm i json-server jsonwebtoken body-parser --save-dew and npm 运行 auth to 运行 server.js
我在 youtube 上学到了这个...
这是我的源代码。有人可以解决我的错误“post”,谢谢!
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
您应该在 server.js 文件
中将路线从 server.post("api/auth/register", (req,res)=>{
更改为 server.post("/api/auth/register", (req,res)=>{
我是 ReactJs 编码的新手,我看过一些关于假 JSON-Server 的视频,但我不知道如何 post 来自 register.js 的所有数据到我的“users.json”到“server.js”。
我所做的是编辑 "package.json" "script": "auth": "node server.js" 和 npm i json-server, npm i json-server jsonwebtoken body-parser --save-dew and npm 运行 auth to 运行 server.js 我在 youtube 上学到了这个...
这是我的源代码。有人可以解决我的错误“post”,谢谢!
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
您应该在 server.js 文件
中将路线从server.post("api/auth/register", (req,res)=>{
更改为 server.post("/api/auth/register", (req,res)=>{