keeping getting 401 not Unauthorized error when trying to get access an records list with authorization

quazzz

quazzz

Posted on September 2, 2024

keeping getting 401 not Unauthorized error when trying to get access an records list with authorization

// axios.js
`import axios from 'axios';

const api = axios.create({
baseURL: 'http://localhost:5000/api',
});

export const setAuthToken = (token) = >{
if (token) {
api.defaults.headers.common['x-auth-token'] = token;
} else {
delete api.defaults.headers.common['x-auth-token'];
}
};

export
default api;
**//login.js**
import React,
{
useState,
useEffect
}
from 'react';
import api,
{
setAuthToken
}
from '../utils/axios';
import AuthForm from '../components/AuthForm';
import {
Navigate
}
from 'react-router-dom';

const Login = () = >{
const[isAuthenticated, setIsAuthenticated] = useState(false);

useEffect(() = >{
  const token = localStorage.getItem('token');
  if (token) {
    setAuthToken(token);
    setIsAuthenticated(true);
  }
},
[]);

const handleLogin = async(formData) = >{
  try {
    const res = await api.post('/auth/login', formData);
    localStorage.setItem('token', res.data.token);
    setAuthToken(res.data.token);
    setIsAuthenticated(true);
  } catch(err) {
    console.error(err.response.data);
  }
};

if (isAuthenticated) {
  return < Navigate to = "/dashboard" / >;
}

return < AuthForm isLogin = {
  true
}
onSubmit = {
  handleLogin
}
/>;
Enter fullscreen mode Exit fullscreen mode

};

export default Login;`
//middleware auth.js

`module.exports = function (req, res, next) {
const token = req.header('x-auth-token');
console.log('Token:', token);
if (!token) return res.status(401).json({ msg: 'No token, authorization denied' });

try {
  const decoded = jwt.verify(token, process.env.JWT_SECRET);
  req.user = decoded.user;
  next();
} catch (err) {
  res.status(401).json({ msg: 'Token is not valid' });
}
Enter fullscreen mode Exit fullscreen mode

};
**//server.js**
const express = require('express')
const router = express.Router()
const Record = require('../models / Records ')
const authmiddleware = require('.. / middleware / auth ')

router.get(' / records ',authmiddleware,async(req,res) => {
try{
const records = await Record.find({userId: req.user._id})
res.json(records)

}
catch(err){
    res.status(500).json({error: 'Ошибкасервера'})
}
Enter fullscreen mode Exit fullscreen mode

})

router.post(' / records ',authmiddleware,async(req,res)=> {
const {date,exercise,weight,reps } = req.body;
try{
const record = new Record({
userId: req.user._id,
date,
exercise,
weight,
reps
})
await record.save()
res.status(201).json(record)
}
catch(err){
res.status(500).json({err: 'Ошибкасервера'})
}
})
router.delete(' / records: id ',authmiddleware, async(req,res)=> {
try{
const record = await Record.findOneAndDelete({_id:req.params.id,userId: req.user._id})
if(!record){
return res.status(404).json({error: 'Записьненайдена'})
}
res.json({message:'Записьудалена'})

}
catch(err){
  res.status(500).json({err: 'Ошибкасервера'})
}
Enter fullscreen mode Exit fullscreen mode

})
module.exports = router`

tried a lot of things , didnt work'

💖 💪 🙅 🚩
quazzz
quazzz

Posted on September 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related