如何将 getAccessToken 与 fetch 函数集成以将数据从 DRF 后端加载到 React 前端? [英] How to integrate getAccessToken with fetch function to load data from DRF backend to React Frontend?

查看:14
本文介绍了如何将 getAccessToken 与 fetch 函数集成以将数据从 DRF 后端加载到 React 前端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里反应新手,但精通 Django.我有一个简单的 fetch 函数,它运行良好,但是我的项目没有涉及登录身份验证.现在我已经配置了登录系统,我的后端拒绝使用任何访问令牌来处理请求.我的登录身份验证对我来说很陌生,或多或少是从某个地方复制过来的.我试图理解它,但无法理解.我只需要知道如何将我的简单提取函数转换为在请求的标头中包含 getAccessToken,以便我的后端处理该请求.

React newbie here, but proficient in Django.I have a simple fetch function which worked perfectly but then my project had no login authentication involved. Now that I have configured the login system, my backend refuses to serve requests with any access tokens. My login authentication is very new to me and was more or less copied from somewhere. I am trying to understand it but am not able to. I just need to know how to convert my simple fetch function to include the getAccessToken along the request in it's headers so my backend serves that request.

这是我以前工作的简单获取功能:

Here is my previously working simple fetch function :

class all_orders extends Component {
  state = {
    todos: []
  };

  async componentDidMount() {
    try {
      const res = await fetch('http://127.0.0.1:8000/api/allorders/'); // fetching the data from api, before the page loaded
      const todos = await res.json();
      console.log(todos);
      this.setState({
        todos
      });
    } catch (e) {
      console.log(e);
    }
  }

我的新登录 JWT 身份验证系统运行良好,但我以前的代码无法正常工作,并且不断出现错误

My new login JWT authentication system works perfectly, but my previous code is not working and I keep getting error

"detail": "未提供身份验证凭据."

"detail": "Authentication credentials were not provided."

这是我无法与我以前的获取功能组合"的访问令牌:

This is is the accesstoken I am not able to 'combine' with my preivous fetch function:

const getAccessToken = () => {
    return new Promise(async (resolve, reject) => {
        const data = reactLocalStorage.getObject(API_TOKENS);

        if (!data)
            return resolve('No User found');

        let access_token = '';
        const expires = new Date(data.expires * 1000);
        const currentTime = new Date();

        if (expires > currentTime) {
            access_token = data.tokens.access;
        } else {
            try {
                const new_token = await loadOpenUrl(REFRESH_ACCESS_TOKEN, {
                    method: 'post',
                    data: {
                        refresh: data.tokens.refresh,
                    }
                });
                access_token = new_token.access;
                const expires = new_token.expires;

                reactLocalStorage.setObject(API_TOKENS, {
                    tokens: {
                        ...data.tokens,
                        access: access_token
                    },
                    expires: expires
                });

            } catch (e) {
                try {
                    if (e.data.code === "token_not_valid")
                        signINAgainNotification();
                    else
                        errorGettingUserInfoNotification();
                } catch (e) {
                    // pass
                }

                return reject('Error refreshing token', e);
            }
        }

        return resolve(access_token);
    });
};

推荐答案

如果您正在寻找一种如何在 fetch 请求中传递标头的方法,它非常简单:

If you're looking for a way how to pass headers in fetch request, it's pretty straight forward:

await fetch('http://127.0.0.1:8000/api/allorders/', {
 headers: {
   // your headers there as pair key-value, matching what your API is expecting, for example:
   'details': getAccessToken()
  }
})

只是不要忘记导入您的 getAccessToken const,如果将它放在另一个文件中,我相信就是这样.关于 Fetch 方法的一些阅读

Just don't forget to import your getAccessToken const, if that's put it another file, and I believe that would be it. Some reading on Fetch method

这篇关于如何将 getAccessToken 与 fetch 函数集成以将数据从 DRF 后端加载到 React 前端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆