Привет, я пытаюсь выполнить проверку с использованием реакции и nodejs, я пытался реализовать это, когда я намеренно меняю токен в sessionStorage, он должен удалить токен и перенаправить на loginPage, вместо этого его удаление, но не перенаправление. .
Вот мой ответ js Код для удаления страницы
import React, { useState, useEffect } from "react";
import { Link, Redirect } from "react-router-dom";
import { responsiveFontSizes } from "@material-ui/core";
export default function DeletePage() {
const [values, setValues] = useState("");
const [loggedIn, setloggedIn] = useState(false);
// useEffect(() => {
// async function fSubmit() {
// try {
// const response = await fetch(
// "http://localhost:4000/auth/delete-user/",
// {
// method: "POST",
// headers: {
// Authorization: `Bearer ${token}`,
// "X-FP-API-KEY": "iphone", //it can be iPhone or your any other attribute
// "Content-Type": "application/json"
// }
// }
// );
// const data = await response.json();
// if (data !== "Authorized User") {
// console.log(data);
// setloggedIn(false);
// sessionStorage.removeItem("token");
// } else {
// console.log(data);
// }
// } catch (error) {
// console.log(error.messsage);
// }
// // setValues(data.data);
// }
// }, []);
async function fSubmitButton(e) {
e.preventDefault();
try {
const response = await fetch("http://localhost:4000/auth/delete-user/", {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"X-FP-API-KEY": "iphone", //it can be iPhone or your any other attribute
"Content-Type": "application/json"
}
});
const data = await response.json();
if (response.status === 403) {
console.log(data);
setloggedIn(false);
sessionStorage.removeItem("token");
} else {
console.log(data);
}
} catch (error) {
console.log(error.messsage);
}
// setValues(data.data);
}
const token = sessionStorage.getItem("token");
console.log(token);
if (!token) {
return <Redirect to="/" />;
}
if (!token) return <Redirect to="/" />;
return (
<div>
<h2>delete</h2>
<button type="submit" onClick={fSubmitButton}>
ccc
</button>
</div>
);
}
Вот мой Node JS код для проверки и генерации токенов
const router = require("express").Router();
const Connection = require("../Database/database");
const jwt = require("jsonwebtoken");
Connection.getConnection(err => {
if (!err) console.log("Connected to Database");
else console.log(err);
});
router.get("/users", (req, res) => {
const query = "select * from users";
Connection.query(query, (err, rows) => {
if (!err) res.json({ data: rows });
else console.log(err);
});
});
router.get("/users/:idusers", (req, res) => {
const id = req.params.idusers;
const query = "select * from users where idusers = ?";
Connection.query(query, id, (error, rows) => {
if (!error) res.json({ data: rows[0] });
else console.log(error);
});
});
// router.get("/getLogin/:username/:password", (req, res) => {
// const user = req.params.username;
// const password = req.params.password;
// // console.log(req.query.username);
// console.log(user);
// // console.log(req.query.password);
// console.log(password);
// const query = `select * from users where username = ?`;
// Connection.query(
// `select * from users where username = ? AND password = ?`,
// [user, password],
// (error, rows) => {
// if (rows.length > 0) res.json({ data: rows[0] });
// // else console.log("ere");
// else res.status(404).json({ error: "Not Found" });
// }
// );
// });
// Only use post request for form submision
router.post("/postLogin/:username/:password", (req, res) => {
const user = req.params.username;
const password = req.params.password;
// console.log(req.query.username);
console.log(user);
// console.log(req.query.password);
console.log(password);
const query = `select * from users where username = ?`;
Connection.query(
`select * from users where username = ? AND password = ?`,
[user, password],
(error, rows) => {
if (rows.length > 0) {
jwt.sign({ rows: user }, "secretley", (err, token) => {
if (err) console.log(err);
// res.json({ data: rows[0], token }); //shouldnt send sensitive datas via jwt
res.json({ token });
});
}
// else console.log("ere");
else res.status(404).json({ error: "Not Found" });
}
);
});
const verifyTheToken = (req, res, next) => {
// getting the token from the header
const bearer = req.headers["authorization"];
if (bearer) {
const bearerToken = bearer.split(" ");
const token = bearerToken[1];
jwt.verify(token, "secretley", (err, data) => {
if (err) {
res.status(403);
} else {
req.userData = data;
console.log(token);
next();
}
});
} else {
res.sendStatus(403);
}
};
router.post("/delete-user", verifyTheToken, (req, res) => {
// bloack 2
console.log("User data block 2:", req.userData);
res.json({ data: "Authorized User" });
});
router.post("/login", (req, res) => {
console.log(req.query);
const { idusers, username, password } = req.query;
const id = req.body.idusers;
const name = req.body.username;
const pass = req.body.password;
console.log(id, name, pass);
});
module.exports = router;