1

I am creating a website using the MERN stack however I don't know how to get data to the frontend that needs authorization from the backend and I tried to console log the problem and it shows me the HTML of my login page even though I am logged in. Any will be appreciated thank you so much.

My backend code:

router.get("/questions", ensureAuthenticated, (req, res) => {
    math = Math.floor(Math.random() * 3) + 1;
    Security.findOne({
        user: req.user.id
    }, (err, user) => {
        if (err) {
            console.log(err);
        }
        if (math === 1) {
            res.send({
                question: user.firstQuestion
            });
        } else if (math === 2) {
            res.send({
                question: user.secondQuestion
            });
        } else {
            res.send({
                question: user.thirdQuestion
            });
        }
    });
});

My Frontend code:

class QuestionForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: ''
        }
    }
    componentDidMount() {
        axios.get("http://localhost:5000/users/questions")
            .then((res) => {
                this.setState({
                    data: res.data
                });
            }).catch((err) => console.log(err));
    }
    render() {
        return <h1 > {
            this.state.data
        } < /h1>
    }
}
kedar sedai
  • 1,687
  • 3
  • 16
  • 25
Gagan
  • 51
  • 8

1 Answers1

0

a lot of changes should be made.

  1. you never want to use the port in your Axios request add to you package.json an proxy attribute

    "proxy": "http://localhost:5000" then you can change your axios get to

    axios.get("/users/questions")

  2. best practice when using autorization is to add to axios interceptors

follow this thread : How can you use axios interceptors?

and also here is an example for using authorization with JWT token

const tokenHandler = axios.create();

tokenHandler.interceptors.request.use(config => {
  const token = localStorage.getItem("token");
  if (token) {
    config.headers["Authorization"] = token;
  }
  return config;
});

export default tokenHandler;

let's say you create a token on the login page and store it inside your local storage.

now you can import the token handler and your request should look something like this :

import {tokenHandler} from '<TOKEN HANDLER PATH>'
..
..

 tokenHandler.get("/users/questions")
           .then((res)=>{
               this.setState({data:res.data});
           }).catch((err)=>console.log(err));
Naor Tedgi
  • 5,204
  • 3
  • 21
  • 48