'CANNOT POST /auth/is-verify - Unexpected token < in JSON at position 0
I am following a video tutorial on login authentication using JWT Tokens.
I have done all the things, registration of the user, logging in the user and also displaying the user info on Dashboard using the token generated on Log in.
Only thing left to do is to verify User Token on Page Refresh so that user doesn't have to log in every time he opens the website, unless the session is expired.
For this purpose, I made a is-verify route in my server side which is as follows,
is-verify route code (Please note this exists in jwAuth.js route file, but I have only shared is-verify route code below)
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;
Code for the middleware authorization.js is as follows,
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");
}
}
Code for my index.js or server.js on the server-side is,
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");
})
Code for the App.js on Client side is,
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;
Code for the Dashbord.js on Client Side is as follows,
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;
The problem I am getting is whenever I log
App.js:25 POST http://localhost:3000/auth/is-verify 404 (Not Found)
Unexpected token < in JSON at position 0
I can't seem to figure out the reason for this.
I checked my Network and according to this, it sends a request to is-verify with the correct token (no issues with the token being sent from client-side), however in the preview of that request, this is what's being returned,
Cannot POST /auth/is-verify
Can anyone kindly help me to solve this issue? I tried to look up this error on internet, but I still couldn't find any answer that solved this issue. As far as I see, the link to which the request is being sent is correct and it is also sending a JSON RESPONSE as in res.json(true) so this shouldn't be an issue.
Solution 1:[1]
In app.js file for client side.
In isAuth() function you are making request to "http://localhost:3000/auth/is-verify" using POST method.
const response = await fetch("http://localhost:3000/auth/is-verify", {
method: "POST",
headers: {token: localStorage.token}
})
But you have declared your route as GET so you need to change method field to GET in isAuth() function or else you can change your is-verify route code and make it to accept POST request.
You can change method in isAuth function to GET.
const response = await fetch("http://localhost:3000/auth/is-verify", {
method: "GET",
headers: {token: localStorage.token}
})
You can also make is-verify route to accept POST request as below.
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jay Godhani |
