【问题标题】:How to get data from the backend that needs authorization using React如何使用 React 从需要授权的后端获取数据
【发布时间】:2020-10-25 10:44:24
【问题描述】:

我正在使用MERN 堆栈创建一个网站,但是我不知道如何将数据获取到需要从后端授权的前端,我试图通过控制台记录问题,它向我显示了HTML我的登录页面,即使我已登录。任何将不胜感激,非常感谢。

我的后端代码:

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
            });
        }
    });
});

我的前端代码:

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>
    }
}

【问题讨论】:

    标签: node.js reactjs express axios mern


    【解决方案1】:

    应该做很多改变。

    1. 你永远不想在你的 Axios 请求中使用端口 给你添加package.json一个代理属性

      "proxy": "http://localhost:5000" 然后你可以改变你的 axios get 到

      axios.get("/users/questions")

    2. 使用自动化的最佳实践是添加到 axios interceptors

    关注这个话题: How can you use axios interceptors?

    这里还有一个使用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;
    

    假设您在登录页面上创建了一个令牌并将其存储在本地存储中。

    现在您可以导入令牌处理程序,您的请求应如下所示:

    import {tokenHandler} from '<TOKEN HANDLER PATH>'
    ..
    ..
    
     tokenHandler.get("/users/questions")
               .then((res)=>{
                   this.setState({data:res.data});
               }).catch((err)=>console.log(err));
    

    【讨论】:

    • 谢谢。我尝试了这个实现,但结果还是一样。
    猜你喜欢
    • 2023-03-11
    • 2016-09-04
    • 2022-01-21
    • 2020-09-28
    • 2020-01-16
    • 1970-01-01
    • 2021-09-23
    • 2017-10-24
    • 2017-05-19
    相关资源
    最近更新 更多