Im trying to send my token from the client:
useEffect(() => {
const verify_token = async () => {
if (token === null){return setLoggedIn(false);}
try {
axios.defaults.headers.common['Authorization'] = token;
const response = await axios.post(`${URL}/verify`)
console.log(response.data.state)
return response.data.state ?
login(token) : logout();
} catch (error) {
console.log(error);
alert.show(error);
setLoggedIn(false)
}
};
verify_token();
},[]);
To my backend for verification:
const verify_token = (req, res) => {
const token = req.headers.Authorization;
console.log(token)
try {
jwt.verify(token, jwt_secret, (err, succ) => {
err
? res.json({ state: false, message: "Token invalid" })
: res.json({ state: true, message: succ });
});
}
catch (error){
console.log(error)
}
};
And I get this Cors-error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3001/verify. (Reason: CORS request did not succeed). Status code: (null).
Routes are configured as follows:
router.options('/verify', cors())
router.options('/enter', cors())
router.post('/enter',cors(), controller.login)
router.post('/verify', cors(), controller.verify_token)
just pass this object into cors function.
const corsOpts = {
origin: 'http://localhost:3001',
methods: [ 'OPTIONS', 'GET', 'POST', 'PUT', 'DELETE' ],
allowedHeaders: '*',
credentials: true
}
and you if you use express then you can use it where your express is init first time like and assign middleware to work for you instead of passing to every route.
const app: Express = express();
app.use(cors(corsOpts);