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

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

问题描述

在这里反应新手,但是精通Django。我有一个简单的访存功能,可以很好地工作,但是我的项目没有登录身份验证。现在,我已经配置了登录系统,我的后端将拒绝使用任何访问令牌为请求提供服务。我的登录认证对我来说是很新的,或多或少是从某个地方复制的。我正在尝试了解它,但无法。我只需要知道如何转换简单的访存函数,以便将请求中的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": "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);
    });
};


推荐答案

如果您正在寻找一种通过方式标头在提取请求中,非常简单:

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天全站免登陆