无法发布 /auth/is-verify - 在位置 0 的 JSON 中意外<令牌



我正在观看一个关于使用JWT令牌登录身份验证的视频教程。

我已经完成了所有的事情,注册用户,登录用户,并使用登录时生成的令牌在仪表板上显示用户信息。

唯一要做的就是在页面刷新时验证用户令牌这样用户就不必每次打开网站都要登录,除非会话已经过期。

为此,我在服务器端创建了一条is-verify路由,如下所示:

-验证路由码(请注意这存在于jwAuth.js路由文件,但我只分享了下面的is-verify路由代码)

router.get("/is-verify", authorization, (res, req) => {
try {
res.json(true); 

} catch (err) {
console.log(err.message); 
res.status(500).send("Server Error")
}
})
module.exports = router;

中间件authorization.js的代码如下,

const jwt = require("jsonwebtoken");
require("dotenv").config();
module.exports = async (req, res, next) => {
try {
const jwtToken = req.header("token");
if (!jwtToken) {
return res.status(403).json("Not Authorized");
}
// In case we do have a token, check if the token is valid or not 
const payload = jwt.verify(jwtToken, process.env.jwtSecret);
req.user = payload.user; 
next(); 
} catch (err) {
console.log(err.message); 
return res.status(403).json("You are not authorized");
}
}

我的index.js或server.js代码在服务器端是

const express = require('express')
const app = express() 
const cors = require('cors')
app.use(express.json()) // Lets you use req.body 
app.use(cors())
// ROUTES 
// Register and Login Routes 
app.use("/auth", require("./routes/jwAuth"));
app.use("/dashboard", require("./routes/dashboard"));

app.listen(3000, () => {
console.log("Console is running");
})
客户端App.js的代码是,
import React, { Fragment, useState, useEffect } from "react";
import "./App.css";
import {
BrowserRouter as Router,
Switch,
Route,
Redirect,
} from "react-router-dom";
import Dashboard from "./components/Dashboard";
import Login from "./components/Login";
import Register from "./components/Register";
function App() {
const [isAuthenticated, setIsAuthenticated] = useState(false); 
const setAuth = (boolean)  => {
setIsAuthenticated(boolean); 
}

async function isAuth() {
try {
const response = await fetch("http://localhost:3000/auth/is-verify", {
method: "POST", 
headers: {token: localStorage.token}
})

const parseRes = await response.json(); 
console.log(parseRes); 
} catch (err) {
console.log(err.message); 

}
}
useEffect(() => {
isAuth(); 
}, [])
return (
<Fragment>
<Router>
<div className="container">
<Switch>
<Route exact path = "/login" render={props => !isAuthenticated ? <Login {...props} setAuth = {setAuth} /> : <Redirect to="/dashboard" />} />
<Route exact path = "/register" render={props => !isAuthenticated ? <Register {...props} setAuth = {setAuth} /> : <Redirect to="/login" />} />
<Route exact path = "/dashboard" render={props => isAuthenticated ? <Dashboard {...props} setAuth = {setAuth}/> : <Redirect to="/login" />} />
</Switch>
</div>
</Router>
</Fragment>
);
}
export default App;

客户端dashboard .js代码如下,

import React, {Fragment, useState, useEffect} from "react"
import { toast } from "react-toastify";
const Dashboard = ({setAuth}) => {
const [name, setName] = useState("")
async function getName() {
try {
const response = await fetch("http://localhost:3000/dashboard", {
method: "GET",  // Fetch is GET Request by default as well. So not typing this would have worked too
headers: {token: localStorage.token}
});
const parseRes = await response.json()
setName(parseRes.user_name); 
console.log(parseRes); 
} catch (err) {
console.error(err.message)

}
}
const logout = async e => {
e.preventDefault();
try {
localStorage.removeItem("token");
setAuth(false);
toast.success("Logout successfully");
} catch (err) {
console.error(err.message);
}
};
useEffect(() => {
getName(); 
}, []);
return (
<Fragment>
<h1 className="mt-5">Dashboard</h1>
<h2>Welcome {name}</h2>
<button onClick={e => logout(e)} className="btn btn-primary">
Logout
</button>
</Fragment>
);
};
export default Dashboard; 

我得到的问题是每当我记录

App.js:25 POST http://localhost:3000/auth/is-verify 404 (Not Found)
Unexpected token < in JSON at position 0

我似乎想不出这个的原因。

我检查了我的网络并据此向is-verify发送请求使用正确的令牌(从客户端发送令牌没有问题),但是在该请求的预览中,这是返回的内容

Cannot POST /auth/is-verify

谁能帮我解决这个问题?我试着在网上查找这个错误,但我仍然找不到任何解决这个问题的答案。据我所知,发送请求的链接是正确的,它也发送了一个JSON响应,如res.json(true)所以这应该不是问题。

客户端在app.js文件中

在isAuth()函数中,您使用POST方法向"http://localhost:3000/auth/is-verify"发出请求。

const response = await fetch("http://localhost:3000/auth/is-verify", {
method: "POST", 
headers: {token: localStorage.token}
})

但是你已经将你的路由声明为GET,所以你需要将isAuth()函数中的方法字段更改为GET,或者你可以更改你的is-verify路由代码并使其接受POST请求。

可以将isAuth函数中的方法改为GET。

const response = await fetch("http://localhost:3000/auth/is-verify", {
method: "GET", 
headers: {token: localStorage.token}
})

你也可以设置is-verify路由来接受POST请求,如下所示。

router.post("/is-verify", authorization, (res, req) => {
try {
res.json(true); 

} catch (err) {
console.log(err.message); 
res.status(500).send("Server Error")
}
})
module.exports = router;

最新更新